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
[ "$var" =~ foo[0-9]+ ]

Correct code:

#!/bin/sh
expr "$var" : '.*foo[0-9]\{1,\}' > /dev/null

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.

Instead, use expr's : operator, which is specified by POSIX. It may be necessary to revise the regular expression because expr uses POSIX 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.

Exceptions:

None

Related resources:

  • Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!

Clone this wiki locally

⌂ 换网址