Rajan Vashisht
Rajan Vashisht

Reputation: 25

Search associate array values for one key in array in bash

I have an associate array that looks like this with a variable declared for user input

NUMBER=$1

declare -A AD
AD[1]=aaaa
AD[2]=bbbb
AD[3]=cccc
AD[4]=dddd
AD[2]=eeee
AD[2]=ffff
AD[4]=gggg

If I want to get a user input number and search through that associative array and display a list of values like like

Let's say if the user entered 2, it should search in that array and return me the output as below: I'm not sure how to do that with search loop if that's what is required to accomplish this.

bbbb
eeee
ffff

Upvotes: 0

Views: 92

Answers (1)

kabanus
kabanus

Reputation: 25895

Each time you

AD[2]=something

You override what was previously there. It seems as though you want the entries (or just this entry) to be a list, which is not allowed, but you could fake it with a string

AD[2]="bbbb eeee ffff"

If you want to return the entry as an array, simply return

(${AD[2]})

This of course only works if you do not have spaces in your words. If you do, deciding on a splitting token and using (${AD[2]//;/ }) would work (with ; as a token). To work with this string based approach, you would have to append your array as follows:

AD[2]+=" aaa"
Dd[2]+=" bbb"
AD[2]+=" ccc"

That way if you want to print given "2" them words one by one then:

for word in ${AD[2]}; do
    echo "$word"
done

Again, by not quoting AD[2] I allow bash to separate the words by spaces. A safer approach, using an agreed about token might be

AD[2]+=";aaa"
AD[2]+=";bbb"
AD[2]+=";ccc"

IFS=";" read -ra arr <<< "${AD[2]}"

for word in "${arr[@]}"; do
    [ -z "$word" ] && continue  # If I always use += to add to the array the first word is empty. Use AD[2]=aaa to avoid this rather than +=.
    echo "$word"
done

Upvotes: 1

Related Questions