Bash is the right way to avoid the dollar in regular expression

What is the correct way to escape the dollar sign in bash regex? I am trying to check if a string starts with a dollar sign. Here is my code in which I run away from the dollar twice in an expression of double quotes:

echo -e "AB1\nAB2\n\$EXTERNAL_REF\nAB3" | while read value; do if [[ ! $value =~ "^\\$" ]]; then echo $value else echo "Variable found: $value" fi done 

This does what I want for a single box that has:

 GNU bash, version 3.2.25(1)-release (x86_64-redhat-linux-gnu) 

And the detailed output shows

 + [[ ! $EXTERNAL_REF =~ ^\$ ]] + echo 'Variable found: $EXTERNAL_REF' 

However, in another field that uses

 GNU bash, version 4.1.2(1)-release (x86_64-redhat-linux-gnu) 

The comparison expands as follows

 + [[ ! $EXTERNAL_REF =~ \^\\\$ ]] + echo '$EXTERNAL_REF' 

Is there a standard / better way to do this that will work in all implementations?

Thank you very much

+4
source share
4 answers

Why are you using regex here? Enough globe:

 #!/bin/bash while read value; do if [[ "$value" != \$* ]]; then echo "$value" else echo "Variable found: $value" fi done < <(printf "%s\n" "AB1" "AB2" '$EXTERNAL_REF' "AB3") 

Works here with shopt -s compat32 .

+2
source

I would replace double quotes with single quotes and delete one \ and get the changes below

 $value =~ "^\\$" 

can also be used as

 $value =~ '^\$' 
+1
source

I did not find a solution either, but for my purposes I settled on the following workaround:

 if [[ "$value" =~ ^(.)[[:alpha:]_][[:alnum:]_]+\\b && ${BASH_REMATCH[1]} == '$' ]]; then echo "Variable found: $value" else echo "$value" fi 

Instead of trying to "indicate" the dollar sign, I instead map everything around, and I fix the symbol where the dollar sign should do a direct string comparison. A little curly, but it works.

As an alternative, I switched to using variables, but just for the backslash character (I don’t like to store the entire regular expression in a variable, because it seems to me that it doesn’t bother that the regular expression does not appear in the context where it was used)

 bs="\\" string="test\$test" if [[ "$string" =~ $bs$ ]]; then echo "output \"$BASH_REMATCH\"" fi 
0
source

The regular expression does not need any quotation marks. This should work:

 if [[ ! $value =~ ^\$ ]]; 
0
source

All Articles