Issue
I have a variable like LINE=foo,bar,,baz
I tried to split this with delimiter ,
using 2 different techniques:
echo ${array[2]}
should return an empty value but it returns baz
(Both treat baz as the 3rd value when it should be the 4th instead.)
Solution
You can do this with read -a
and an alternate delimiter:
IFS=, read -a array <<<"$LINE"
Note that since the assignment to IFS
is a prefix to the read
command, it only applies to that one command, and you don't have to set it back to normal afterward. Also, unlike the ones that depend on word-splitting of unquoted variables, it won't try to "expand" any entries that look like filename wildcards into lists of matching files.
Demo:
$ LINE=foo,bar,,baz
$ IFS=, read -a array <<<"$LINE"
$ declare -p array
declare -a array='([0]="foo" [1]="bar" [2]="" [3]="baz")'
Answered By - Gordon Davisson Answer Checked By - Terry (WPSolving Volunteer)