Reputation: 141
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
Upvotes: 0
Views: 38
Reputation: 121397
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}"
Upvotes: 1