在 Bash 中使用变量作为案例模式 [英] Using variable as case pattern in Bash
本文介绍了在 Bash 中使用变量作为案例模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试编写一个在 case 语句中使用变量作为模式的 Bash 脚本.但是我就是无法让它工作.
I'm trying to write a Bash script that uses a variable as a pattern in a case statement. However I just cannot get it to work.
案例陈述:
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)代码>.也没有成功.
I've tried this with assigning $test
as aaa|bbb|ccc
, (aaa|bbb|ccc)
, [aaa,bbb,ccc]
and several other combinations. I also tried these as the pattern in the case statement: @($test)
, @($(echo $test))
, $($test)
. Also no success.
编辑
为清楚起见,我希望该变量代表多个模式,如下所示:
For clarity, I would like the variable to represent multiple patterns like this:
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 中使用变量作为案例模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文