简体   繁体   中英

Store regex pattern in a variable in bash script

I have the following bash script code:

GOAL="${1:-help}"
TARGET="${2}"
MODULES_LIST="app|tester"

echo "-> Running $TARGET..."
MODULES_LIST_PATTERN = "^($MODULES_LIST)$"
if [[ "$TARGET" =~ $MODULES_LIST_PATTERN ]]; then
    run_${TARGET}
else
    print_error "You must include an existing module: {$MODULES_LIST}"
    exit 1
fi

As you can see, I have a MODULES_LIST variable where I store the modules supported by the application, then I create a regex pattern MODULES_LIST_PATTERN containing the value of the previous var, and use it to check if the provided parameter matches any of the modules. However, it is not working as expected, since when I run ./myscript.sh run app it prints ERROR] You must include an existing module: {app|tester} .

Could someone tell me the proper way of doing this?

My fault... the problem is MODULES_LIST_PATTERN = "^($MODULES_LIST)$" , you can't have whitespaces surrounding the equals sign. After fixing that, it works as expected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM