V.Collette V.Collette - 3 months ago 9
Bash Question

Regexp in a variable Shell

I'm doing some regexp in shell to find coding style error in *.c files.
Actually I'm doing something like this:

# Operator <
if [[ "$1" =~ ([^ ]<|<[^ =$]) ]]; then
warn "$wmsg_space_operator (operator: <)"
fi


But I want to do it like this:

# Operator <
regexpOp=([^ ]<|<[^ =$])
if [[ "$1" =~ $regexpOp ]]; then
warn "$wmsg_space_operator (operator: <)"
fi


How can I do?

Answer

Put regexpOp in quotes

regexpOp='([^ ]<|<[^ =$])'

and rest is assured

Why?

Your regex string contain spaces and anything after the space will be counted as another command.