简体   繁体   English

Unix shell脚本如何测试所有数组值是否等于特定值?

[英]Unix shell script how to test all the array values is equal to particular value?

I Have three array variables like var[1]=1 var[2]=1 var[3]=1 Now i want to check all these three array variables is equal to 1 or not using if command. 我有三个数组变量,如var [1] = 1 var [2] = 1 var [3] = 1现在我要检查所有这三个数组变量是否等于1或不使用if命令。

I tried something like 我尝试了类似的东西

if [[ ${var[@] == 1 ]]; then
echo "Yes"
else
echo "No"
fi

The result of the above code should be Yes but i'm getting No as an answer. 以上代码的结果应为“是”,但我得到了“否”作为答案。

Can anyone please help me on this? 有人可以帮我吗?

${var[@]} will expand to 1 1 1 which is most definitely not equal to 1 . ${var[@]}将扩展为1 1 1 ,这绝对等于1

You can use something like: 您可以使用类似:

rc=Yes
for val in ${var[@]} ; do
    if [[ ${val} != 1 ]]; then
        rc=No
    fi
done
echo $rc

or the more succinct: 或更简洁:

rc=Yes
for v in ${var[@]}; do [[ $v == 1 ]] || rc=No; done
echo $rc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM