Skip to content
Lawrence Velázquez edited this page Mar 9, 2024 · 8 revisions

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

Related resources:

ShellCheck

Each individual ShellCheck warning has its own wiki page like SC1000. Use GitHub Wiki's "Pages" feature above to find a specific one, or see Checks.

Clone this wiki locally