1

I have been struggling with a new concept to me - associative arrays in a bash script.

Here is simplified version of my code:

#!/bin/bash
declare -A MYID
MYID[hello]=world
tac /home/user/filename | while read -r line; do
  MYID[hello]=me
done
echo "${MYID[hello]}"
exit

This is what I thought it would do: 1) declare an associative array called MYID 2) in MYID assign the value world to the key hello 3) read the file /home/user/filename backwards line by line 4) every time it reads a line assign me to the key hello in the MYID array 5) print out "me" and exit

What it does do is print out "world" instead of "me". What am I doing wrong?

1 Answer 1

2

The pipe creates a subshell, so any changes you make to MYID in the while loop only exist in that subshell. Try this instead:

while read -r line; do
    MYID[hello]=me
done < <(tac /home/user/filename)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank-you, this seems to work. I will add this to my list of things to learn.

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.