0

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

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @Kabanus for your response, Well, I want to distinctively list every repeated value in that list if that matches the criteria. If the associative array does not allow that, I'm fine with a different approach too.
@RajanVashisht Using an array is fine, you just need to decide how save your words. I gave full examples.

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.