case 语句中的正则表达式

Mud*_*gie 2 bash regular-expression case

我很难让正则表达式匹配在 bash case 语句中工作。

示例代码:

#!/bin/bash                          

str='    word1 word2'

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

echo "With case:"
case "$str" in
    '^\s*\<word1\>') echo "$str" ;;
esac
Run Code Online (Sandbox Code Playgroud)

该示例适用于 grep,但不适用于案例......我很困惑,因为一些更简单的正则表达式适用于案例。case 是否对正则表达式使用不同的语法?我只是没有正确地逃避事情吗?

Mic*_*alH 9

那是因为case不使用正则表达式,而是使用 bash Pathname Expansion。您可以从 bash 手册页或Bash 参考手册中了解更多信息。