0

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.

Jacob C
  • 53
  • 1
  • 7
  • 1
    The first step in debugging shell scripts is to put `set -x` at the beginning. Then you'll see a trace of all the commands, with variables expanded. – Barmar Oct 15 '19 at 16:43
  • The file contains `banana salad`, but you used `banana sandwich` in the script. – Barmar Oct 15 '19 at 16:46
  • I tried your script I got `1 2 4 5`. The blank is because of the above typo. – Barmar Oct 15 '19 at 16:48
  • 1
    Make sure the file ends with a newline. `read` will return an error if the line ends with EOF, although it will still set the variables. – Barmar Oct 15 '19 at 16:49

1 Answers1

0

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!

Jacob C
  • 53
  • 1
  • 7