I'm using the =~ in one of my Bash scripts. However, I need to make the script compatible with Bash versions that do not support that operator, in particular the version of Bash that ships with msysgit which is not build against libregex. I have a work-around that uses expr match instead, but that again does not work on Mac OS X for some reason.
Thus, I want to use the expr match only if [ -n "$MSYSTEM" -a ${BASH_VERSINFO[0]} -lt 4 ] and use =~ otherwise. The problem is that Bash always seems to parse the whole script, and even if msysgit Bash would execute the work-around at runtime, it still stumbles upon the =~ when parsing the script.
Is it possible to conditionally execute code in the same script depending on the Bash version, or should I look into another way to address this issue?
In your case, you can replace the regular expression with an equivalent pattern match.
[[ $foo = \[+([0-9])\][[:space:]]* ]]
Some explanations:
Patterns are matched against the entire string. The following regexes and patterns are equivalent:
^foo$ and foo^foo and foo*foo$ and *foofoo and *foo*+(...) matches one or more occurrences of the enclosed pattern, which in this case is [0-9]. That is, if $pattern and $regex match the same string, then so do +($pattern) and ($regex)+.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With