Lorccan
Lorccan

Reputation: 823

Looking up an array index by value in bash 3.x

I call this script with: ./script_name 604

#!/bin/bash

switchedChannel=($1)
channelArray=('108' '162' '163' '604' '141' '113')

for array_item in "${channelArray[@]}"; do
    if [[ $array_item == ${switchedChannel[0]} ]] then
        "$array_item MATCHES"
    fi
done

Is there a way to get the index of the array_item that matches (or otherwise get the position of the matched item in the array) without simply using a var as a counter and using this to do the iteration?

There will always be a match, but the array values are unique so there's only one match.

(I am asking because I need then to do something with the array items that are NOT matched, so my thinking is to remove the matched one from the array. I could move the unmatched items to a new array which is fine for a short list, but it would be preferable to terminate the loop as soon as the match is made.)

Upvotes: 1

Views: 1453

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 296049

"${!array[@]}" will iterate over indices, rather than values.

#!/bin/bash

switchedChannel=$1
channelArray=('108' '162' '163' '604' '141' '113')

for array_idx in "${!channelArray[@]}}"; do
    array_item=${channelArray[$array_idx]}
    if [[ $array_item = "$switchedChannel" ]] then
        "$array_item MATCHES at index $array_idx"
    fi
done

That said, for your use case -- where anything you're doing a lookup by is a non-negative integer -- you can do better:

declare -a channelArray=( [108]=1 [162]=2 [163]=3 [604]=4 [141]=5 [113]=6 )
echo "${channelArray[$switchedChannel]}"

This creates a sparse array where the keys are numbers 108, 162, etc.; and the values are 1, 2, 3, etc.

Upvotes: 4

Related Questions