Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write conditional code depending on Bash version / features?

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?

like image 828
sschuberth Avatar asked Jul 16 '26 10:07

sschuberth


1 Answers

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:

    1. ^foo$ and foo
    2. ^foo and foo*
    3. foo$ and *foo
    4. foo 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)+.

like image 136
chepner Avatar answered Jul 19 '26 10:07

chepner