Search code examples
arraysbashifs

How does splitting string to array by 'read' with IFS word separator in bash generated extra space element?


With only one character for IFS, it works fine:

shell@kernel: ~> l="2.4.3"; IFS="." read -a la <<< "$l"; for ((i = 0; i < ${#la[@]}; ++i)) do echo ${la[$i]}; done;
2
4
3

While there are two characters for IFS, extra space element generated

shell@kernel: ~> l="2->4->3"; IFS="->" read -a la <<< "$l"; for ((i = 0; i < ${#la[@]}; ++i)) do echo ${la[$i]}; done;
2

4

3
shell@kernel: ~> l="2..4..3"; IFS=".." read -a la <<< "$l"; for ((i = 0; i < ${#la[@]}; ++i)) do echo ${la[$i]}; done;
2

4

3

How can I get rid of the extra space element in the array?


Solution

  • Continuing from the comment, you can either test for an empty element before storing the value in the array, or you can deal with the empty value when you echo it. Frankly, its simpler to do the latter, e.g.

    l="2->4->3"; IFS="->" read -a la <<< "$l"; \
    for ((i = 0; i < ${#la[@]}; ++i)) do \
    [ -n "${la[i]}" ] && echo ${la[$i]}; done
    

    Output

    2
    4
    3