I'm having a hard time getting regex matches to work in a bash case statement.

Example code:


str='    word1 word2'

echo "With grep:"
echo "$str" |grep '^\s*\<word1\>'

echo "With case:"
case "$str" in
    '^\s*\<word1\>') echo "$str" ;;

The example works with grep, but not with case... I'm confused, because some simpler regexes work with case. Does case use a different syntax for regex? Am I just not escaping things properly?

  • 1
    case does not support regex, it supports shell globbing.
    – heemayl
    Jun 10 '16 at 17:33

That is because case doesn't use regex's but bash Pathname Expansion. You can learn more from bash man page or from Bash Reference Manual.

  • Great to link to the manual. Dec 1 '19 at 11:31

Not the answer you're looking for? Browse other questions tagged or ask your own question.