如何检查BASH列表中是否存在变量 [英] How do I 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.
添加:
说的是:
Addition:
Say list is:
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屋!
查看全文