For the past 2 days I've been trying to learn bash, I've understood a lot about substitution but I'm still struggling to fully understand how escaping works in different scenarios in bash. this is the example I'm practising with.
set -x
string='mo$ney'
echo ^mo\$ney # the shell escapes the $ sign and the backslash disappears
if [[ $string =~ ^mo\$ney$ ]] # the shell keeps the backslash and the string is matched as having a dollar sign.
then
echo "matched"
else
echo "no"
fi
this is what I would expect to write to have it work but it doesn't. my thought process is to escape the backslash to keep a real backslash and escape the dollar sign
if [[ $string =~ ^mo\\\$ney$ ]]
then
echo "matched"
else
echo "no"
fi
I use regular expression in general and if I were creating a regex normally the dollar sign would match the end of a string. so if I wanted to match an actual dollar sign I would escape it in the context of the regex like this /$/ that's the actual regex if I had to create a string that has a regex inside it, I would have to escape the backslash because most languages would use the backslash as a method to escape special characters in strings. so my string would look like this '\$'
to me, it looks like bash skips a step it goes directly from expecting a parameter ($ney
) and when I escape it (\$ney
) it goes directly to being a literal dollar sign.
In my mind, I expect in shell context the parameter expectation to be escaped.
then in the regex context, it should be seeing a $
sign which represents the end of a string
so I expect that to also be escaped to get to \$
in the context of regular expressions.
without this process (the one in my head), I'm not sure how you would match using the regex dollars sign (that is, the end of string token) strangely enough, if I place a $ sign at the end of the matching pattern it works and is taken as being an "end-of-line" regex token ($). this can also be seen outside conditionals
echo money$ # in this situation if the dollar sign is at the end the shell doesn't even need it escaped ♂️. it understands that this is a real dollar sign.
Can anyone offer some clarification on what is going on in conditionals? I've read about how it prevents word splitting and how using quotes inside it while matching makes it match against a literal string and not a pattern (so using string is not even an option).