在Bash中,测试数组是否包含某个值的最简单方法是什么?
编辑:在答案和评论的帮助下,经过一些测试后,我想出了这个:
function contains() {
local n=$#
local value=${!n}
for ((i=1;i < $#;i++)) {
if [ "${!i}" == "${value}" ]; then
echo "y"
return 0
fi
}
echo "n"
return 1
}
A=("one" "two" "three four")
if [ $(contains "${A[@]}" "one") == "y" ]; then
echo "contains one"
fi
if [ $(contains "${A[@]}" "three") == "y" ]; then
echo "contains three"
fi
Run Code Online (Sandbox Code Playgroud)
我不确定它是否是最佳解决方案,但似乎有效.
我有一系列动物:
declare -A animals=()
animals+=([horse])
Run Code Online (Sandbox Code Playgroud)
我想检查动物是否存在:
if [ -z "$animals[horse]"]; then
echo "horse exists";
fi
Run Code Online (Sandbox Code Playgroud)
但这不起作用.