8 SC3015
Lawrence Velázquez edited this page 2024-03-08 23:21:13 -05:00

In POSIX sh, =~ regex matching is undefined.

Problematic code:

#!/bin/sh
if [ "$var" =~ foo[0-9]+ ]; then
  echo matched
fi

Correct code:

#!/bin/sh
# Use the x-hack to handle strings like '('.
if expr "X$var" : 'X.*foo[0-9]\{1,\}' >/dev/null; then
  echo matched
fi

or

#!/bin/sh
case $var in
  *foo[0-9]*)
    echo matched
    ;;
esac

Rationale:

You are using =~ in a script declared to be compatible with POSIX sh or Dash, but =~ is not specified by POSIX and is unlikely to work outside [[ ]] in Bash and Ksh.

Use expr's : operator instead. It may be necessary to revise the regular expression because POSIX expr uses basic regular expressions anchored to the beginning of the string, as opposed to the unanchored extended regular expressions used by [[ str =~ re ]] in Bash and Ksh.

Alternately, use case if the matching can be done with shell patterns instead of regular expressions. This avoids the need for an external utility.

Exceptions:

None