我试图在bash中编写一个脚本,检查用户输入的有效性。
我想将输入(变量x)匹配到一个有效值列表。
我现在想到的是:
for item in $list
do
if [ "$x" == "$item" ]; then
echo "In the list"
exit
fi
done
我的问题是,如果有更简单的方法,
对于大多数编程语言,类似list.contains(x)。
列表是:
list="11 22 33"
我的代码将只对这些值回显消息,因为list被视为数组而不是字符串,
所有的字符串操作都将验证1,而我希望它失败。
Matvey是对的,但你应该引用$x,并考虑任何类型的“空格”(例如新行)
[[ $list =~ (^|[[:space:]])"$x"($|[[:space:]]) ]] && echo 'yes' || echo 'no'
所以,即。
# list_include_item "10 11 12" "2"
function list_include_item {
local list="$1"
local item="$2"
if [[ $list =~ (^|[[:space:]])"$item"($|[[:space:]]) ]] ; then
# yes, list include item
result=0
else
result=1
fi
return $result
}
然后结束
`list_include_item "10 11 12" "12"` && echo "yes" || echo "no"
or
if `list_include_item "10 11 12" "1"` ; then
echo "yes"
else
echo "no"
fi
注意,在变量的情况下必须使用"":
`list_include_item "$my_list" "$my_item"` && echo "yes" || echo "no"
考虑利用关联数组的键。我认为这优于正则表达式/模式匹配和循环,尽管我还没有对其进行分析。
declare -A list=( [one]=1 [two]=two [three]='any non-empty value' )
for value in one two three four
do
echo -n "$value is "
# a missing key expands to the null string,
# and we've set each interesting key to a non-empty value
[[ -z "${list[$value]}" ]] && echo -n '*not* '
echo "a member of ( ${!list[*]} )"
done
输出:
1是(1,2,3)的成员
2是(1,2,3)的一个元素
3是(1,2,3)的一个元素
4不是(1,2,3)的成员