在Bash中将变量用作案例模式 [英] Using variable as case pattern in Bash
本文介绍了在Bash中将变量用作案例模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试编写一个Bash脚本,该脚本在case语句中使用变量作为模式.但是我只是无法使它正常工作.
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]
和其他几种组合来进行此操作.我还尝试了这些作为case语句中的模式:@($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屋!
查看全文