gpt4 book ai didi

bash - 在 Bash 中使用变量作为案例模式

转载 作者:行者123 更新时间:2023-11-29 08:44:43 25 4
gpt4 key购买 nike

我正在尝试编写一个 Bash 脚本,该脚本使用变量作为 case 语句中的模式。但是,我就是无法让它工作。

案例陈述:

case "$1" in
$test)
echo "matched"
;;
*)
echo "didn't match"
;;
esac

我试过将 $test 分配为 aaa|bbb|ccc, (aaa|bbb|ccc), [aaa,bbb,ccc] 和其他几个组合。我还尝试将这些作为案例语句中的模式:@($test)@($(echo $test))$($test) 。也没有成功。

为清楚起见,我希望变量代表多个模式,如下所示:

case "$1" in
aaa|bbb|ccc)
echo "matched"
;;
*)
echo "didn't match"
;;
esac

最佳答案

您可以使用 extglob 选项:

#! /bin/bash

shopt -s extglob # enables pattern lists like +(...|...)
test='+(aaa|bbb|ccc)'

for x in aaa bbb ccc ddd ; do
echo -n "$x "
case "$x" in
$test) echo Matches.
;;
*) echo Does not match.
esac
done

关于bash - 在 Bash 中使用变量作为案例模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13254425/

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