Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash - correct way to escape dollar in regex

What is the correct way to escape a dollar sign in a bash regex? I am trying to test whether a string begins with a dollar sign. Here is my code, in which I double escape the dollar within my double quotes expression:

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 one box which has:

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

And the verbose output shows

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

However, on another box which uses

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

The comparison is expanded as follows

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

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

Many thanks

like image 674
user1198484 Avatar asked Dec 27 '12 09:12

user1198484


1 Answers

Why do you use a regular expression here? A glob is enough:

#!/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.

like image 135
gniourf_gniourf Avatar answered Sep 28 '22 14:09

gniourf_gniourf