1

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.

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?

1
  • 2
    You are missing }. Also, you can't check whole array like that. ${var[@]} will be "1 1 1", which is not equal to "1". Commented Nov 20, 2014 at 4:06

1 Answer 1

2

${var[@]} will expand to 1 1 1 which is most definitely not equal to 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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.