检查Bash列表中是否存在变量 [英] Check if a variable exists in a list in Bash
本文介绍了检查Bash列表中是否存在变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试用bash编写脚本来检查用户输入的有效性.
我想将输入(例如变量 x
)与有效值列表匹配.
I am trying to write a script in bash that check the validity of a user input.
I want to match the input (say variable x
) to a list of valid values.
我现在想出的是:
for item in $list
do
if [ "$x" == "$item" ]; then
echo "In the list"
exit
fi
done
我的问题是,是否有更简单的方法可以做到这一点,
大多数编程语言都类似于 list.contains(x)
.
My question is if there is a simpler way to do this,
something like a list.contains(x)
for most programming languages.
说的是:
list="11 22 33"
由于 list
被视为数组而不是字符串,因此
我的代码将仅针对这些值回显消息,所有的字符串操作都将验证 1
,而我希望它失败.
my code will echo the message only for those values since list
is treated as an array and not a string,
all the string manipulations will validate 1
while I would want it to fail.
推荐答案
[[ $list =~ (^|[[:space:]])$x($|[[:space:]]) ]] && echo 'yes' || echo 'no'
或创建一个函数:
contains() {
[[ $1 =~ (^|[[:space:]])$2($|[[:space:]]) ]] && exit(0) || exit(1)
}
使用它:
contains aList anItem
echo $? # 0: match, 1: failed
这篇关于检查Bash列表中是否存在变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文