Search code examples
bashshellunixifs

Prevent IFS to stop on new lines


I have a multiline string which I want to transform into an array by using a single delimiter |. However, when setting IFS=| it will stop right before a new line appears:

IFS='|' read -a VARS <<< "var1|var2|var3
                          var4|var5|var6
                          var7|var8|var9"

echo ${VARS[@]}
#output => var1 var2 var3

I am wondering why the remaining lines won’t be evaluated and how to prevent that of happening, being able to assign every variable regardless the presence of a new line?


Solution

  • Set your IFS to | and \n and use -d to use another delimiter besides newline. You also need to keep your values intact. Spaces also get to be included.

    IFS=$'|\n' read -d '' -a VARS <<< "var1|var2|var3
    var4|var5|var6
    var7|var8|var9"
    

    read by default only reads up to the first newline character unless changed by -d. '' is also synonymous to $'\0' as an argument to it.

    Another point

    Spaces (including newlines) inside double-quotes are not silently ignored. They are also included literally as a value.

    So perhaps what you really should have done is:

    IFS='|' read -a VARS <<< "var1|var2|var3|var4|var5|var6|var7|var8|var9"