gpt4 book ai didi

bash - 使用括号对表达式进行分组以防万一

转载 作者:行者123 更新时间:2023-12-03 23:59:18 24 4
gpt4 key购买 nike

我想在 case 中用 () 对表达式进行分组,如下所示:

case a in
'*(a|b)*') printf '%s\n' 'something something';;
esac

但这并没有取得任何成功。我也试过:

*(a|b)**'('a|b')'*我都没有成功。

最佳答案

这将是特定于 Bash 的:

您需要启用 extglob 并使用此特定语法

#!/usr/bin/env bash

shopt -s extglob

case "$1" in
*@(a|b)*) printf '%s\n' 'something something';;
esac

参见man bash:

If the extglob shell option is enabled using the shopt builtin, several extended pattern matching operators are recognized. In the following description, a pattern-list is a list of one or more patterns separated by a |. Composite patterns may be formed using one or more of the following sub-patterns:

  • ?(pattern-list)
    Matches zero or one occurrence of the given patterns
  • *(pattern-list)
    Matches zero or more occurrences of the given patterns
  • +(pattern-list)
    Matches one or more occurrences of the given patterns
  • @(pattern-list)
    Matches one of the given patterns
  • !(pattern-list)
    Matches anything except one of the given patterns

或者,您可以使用命令组末尾的特殊 ;& 标记让 case 继续执行下一个模式的命令组。

这是 NOT POSIX,但由 bashkshksh 处理strong>zsh 仍然:

#!/usr/bin/env ksh

case "$1" in
*a*) ;& # Continue to next commands group
*b*) printf '%s\n' 'something something';;
esac

现在,that other guy在评论中指出。

POSIX 方式:

#!/usr/bin/env sh

case "$1" in
*a*|*b*) printf '%s\n' 'something something';;
esac

关于bash - 使用括号对表达式进行分组以防万一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64418402/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com