如何在bash脚本中的case语句中使用模式?

Ram*_*ela 70 bash case-statement

man页面说该case语句使用"文件名扩展模式匹配".
我通常想要一些参数的短名称,所以我去:

case $1 in
    req|reqs|requirements) TASK="Functional Requirements";;
    met|meet|meetings) TASK="Meetings with the client";;
esac

logTimeSpentIn "$TASK"
Run Code Online (Sandbox Code Playgroud)

我尝试过类似req*或者me{e,}t我理解的模式可以正确扩展以匹配文件名扩展上下文中的值,但它不起作用.

Pau*_*ce. 135

支撑扩展不起作用,但是*,?并且[]做到了.如果你设置了shopt -s extglob那么你也可以使用扩展模式匹配:

  • ?() - 零次或一次出现模式
  • *() - 零次或多次出现模式
  • +() - 一次或多次出现模式
  • @() - 一次出现模式
  • !() - 除模式外的任何东西

这是一个例子:

shopt -s extglob
for arg in apple be cd meet o mississippi
do
    # call functions based on arguments
    case "$arg" in
        a*             ) foo;;    # matches anything starting with "a"
        b?             ) bar;;    # matches any two-character string starting with "b"
        c[de]          ) baz;;    # matches "cd" or "ce"
        me?(e)t        ) qux;;    # matches "met" or "meet"
        @(a|e|i|o|u)   ) fuzz;;   # matches one vowel
        m+(iss)?(ippi) ) fizz;;   # matches "miss" or "mississippi" or others
        *              ) bazinga;; # catchall, matches anything not matched above
    esac
done
Run Code Online (Sandbox Code Playgroud)

  • 链接到这些文档:https://www.gnu.org/software/bash/manual/html_node/Pattern-Matching.html#Pattern-Matching (2认同)

plu*_*dra 40

我不认为你可以使用大括号.

根据Bash手册关于条件构造中的案例.

每个模式经历波浪扩展,参数扩展,命令替换和算术扩展.

不幸的是,Brace Expansion没什么.

所以你必须做这样的事情:

case $1 in
    req*)
        ...
        ;;
    met*|meet*)
        ...
        ;;
    *)
        # You should have a default one too.
esac
Run Code Online (Sandbox Code Playgroud)


Cir*_*四事件 8

ifgrep -Eq

arg='abc'
if echo "$arg" | grep -Eq 'a.c|d.*'; then
  echo 'first'
elif echo "$arg" | grep -Eq 'a{2,3}'; then
  echo 'second'
fi
Run Code Online (Sandbox Code Playgroud)

在哪里:

  • -q防止grep产生输出,它只产生退出状态
  • -E 启用扩展正则表达式

我喜欢这个因为:

一个缺点是这可能比case调用外部grep程序慢,但我倾向于在使用 Bash 时最后考虑性能。

case 是 POSIX 7

默认情况下shopt,Bash 似乎遵循 POSIX 而没有提到/sf/answers/318918561/

这是引用:http : //pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_01 “案例条件构造”部分:

条件构造案例应执行与多个模式中的第一个相对应的复合列表(请参阅模式匹配表示法)[...] 具有相同复合列表的多个模式应由“|”分隔 象征。[...]

case 结构的格式如下:

case word in
     [(] pattern1 ) compound-list ;;
     [[(] pattern[ | pattern] ... ) compound-list ;;] ...
     [[(] pattern[ | pattern] ... ) compound-list]
  esac
Run Code Online (Sandbox Code Playgroud)

然后http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_13部分“2.13. 模式匹配符号”只提到?,*[]