0

I have an array -

val=(4196976 4601313 4242010 0 3581283 2392831 3176852 3205880 3794451 0 3627872)

I am trying to find the index of all the elements whose values are equal to 0

How can i achienve this?

This is what i have tried -

for ((i = 1; i <= 10; i++)); do
    if [ "$i" -eq "0" ]; then
            echo "Index: $i, value: ${val[i]}"
    fi
done

The output should be

Index: 3, value: 0
Index: 9, value: 0

2 Answers 2

4

If the array has gaps in it, it might be better to loop over the indices of the array instead:

for i in "${!val[@]}"
do
    if [[ ${val[i]} -eq 0 ]]
    then
        echo "Index: $i, value: ${val[i]}"
    fi
done

So, if your array was like:

val=([100]=327823 [54]=0 [787998]=377463287)

You'd still get 54 as the index.

This should also work for associative arrays (strings as indices instead of integers).

2
#!/bin/bash
val=(4196976 4601313 4242010 0 3581283 2392831 3176852 3205880 3794451 0 3627872)
n=0
for i in ${val[@]}; do
    [ $i -eq 0 ] && echo Index: $n, value: $i
    ((n++))
done

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .