There are two basic problems here: setting IFS
affects a lot of things in how the shell parses strings, including some you're not expecting; and leaving $3
unquoted allows it to be one of the things that gets messed up.
What's happening is that when you refer to $3
without double-quotes around it, the shell splits it into "words" using $IFS
as separator(s). In your example, this yields three words: "Option 1", "Option 2", and "Option 3". In the context of <<<
, it then splices them back together using a space as a separator (which is weird, but that's what it does), yielding "Option 1 Option 2 Option 3". You can see this effect separately:
$ foo="Option 1,Option 2,Option 3"
$ IFS=,
$ cat <<< $foo
Option 1 Option 2 Option 3
So then the read
command gets "Option 1 Option 2 Option 3" as input, splits it based on $IFS
(","), finds that there are no word separators, so it puts it all in element #0 of optionList
.
You can fix this by double-quoting $3
to prevent word-splitting, but you're going to have other problems because IFS
is also going to affect lots of other things throughout your script. So you should also follow anubhava's recommendation to make the IFS
assignment a prefix on the read
command, so that it only affects that one command rather than being a global change to how the shell parses strings.
So, with both changes, my recommendation is to use:
IFS=, read -ra optionList <<< "$3"
... just like anubhava's recommendation.