I'm referencing How to define hash tables in Bash? for my work. I'm attempting to parse a dict.csv file containing test data like this:
1,orange
2,apple
3,banana sandwich
4,grape juice
5,strawberry
And using the Bash 4 solution, creating a key/value dictionary. Here is my current code (note the key/value in while is inverted, this is intentional):
declare -A dict
fileName="dict.csv"
OIFS=$IFS
IFS=','
while read value key
do
dict+=( ["$key"]="$value" )
done < $fileName
IFS=$OIFS
echo ${dict["orange"]}
echo ${dict["apple"]}
echo ${dict["banana sandwich"]}
echo ${dict["grape juice"]}
echo ${dict["strawberry"]}
I would expect my output to be:
1
2
3
4
5
But instead my output is:
1
2
3
<blank>
<blank>
I noticed that the number of blank lines is equivalent to the number of keys with spaces in them (e.g. banana salad
and grape juice
). I'm assuming this problem stems from my misunderstanding of how IFS, the while loop, and parsing in bash work but I'm at a loss to understand what i'm missing.
Thank you for any insights.
Edit: Made a typo in the contents of the dict.csv, 3 now contains banana sandwich
and not banana salad
as previously stated. This was a typo in the question and not in my code. My apologies.
I found my problem. Thank you for Barmar for pointing this out. My dict.csv did not end with a newline which caused a parsing error. There were other issues but they are unrelated to this question. Thank you for the help!