0

I've been trying to storage my data in an array as follows:

table="$1"
reference="$2"
directory="$3"

declare -A count

$reference | while read line; do
    ref=`echo $line | cut -d " " -f1`
    key=`echo $line | cut -d " " -f4`
    count=([$key]=$ref)
    echo $ref
    echo $key
    echo "${count[$key]}"
 done

This works, I do the prints and for each key I got the value I want. Then, I try to use with some keys:

cat $table | while read line; do
    sample=`echo $line | cut -d "_" -f1`
    id=${count[$line]}
    echo $sample
    echo $line
    echo $id
    echo "works"
done

Here is the problem: Sample is echoed perfectly, just as are $line and "works". But $id is not working, and I have no idea what I am missing here

1 Answer 1

1

That's because whatever you store in count are gone as soon as the subshell that runs the while loop exits. The while loop that you pipe into runs in a subshell. So any variables you "set" won't be available outside if it. That means when you later use count, it doesn't have any elements.

Change the loop to:

while IFS= read -r line; do
    ref=`echo $line | cut -d " " -f1`
    key=`echo $line | cut -d " " -f4`
    count["$key"]="$ref"
    echo $ref
    echo $key
    echo "${count[$key]}"
 done < "${reference}"

Similarly change in the other loop.

I am assuming reference is a file. If reference is actually the text you want to read the "lines" from then you can use here strings:

while IFS= read -r line; do
    ...
    ...  
done <<< "${reference}"
Sign up to request clarification or add additional context in comments.

10 Comments

shouldn't declare -A count deal with that?
No. It just declares an array. It's not related to the issue. The count that's updated inside the loop is not same one you have outside. Inside the subshell, it's a different variable and doesn't exist once the subshell exits.
Not to mention that count=(...) is creating a new array each time and blowing up any old contents.
@EtanReisner Thanks for pointing it out. I didn't see it at all. I think, it should be fine now.
Yeah, that's not it. You want count+=(["$key"]="$ref") I believe.
|

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.