Working in BASH GNU bash, version 4.2.25(1)-release (x86_64-pc-linux-gnu) under Ubuntu 12.04LTS
I'm having an issue with writing the contents of an array into a string delimited by new lines.
I have found this entry (How do I convert a bash array variable to a string delimited with newlines?), which gave me great hope that the solution was to hand. This works on the command line perfectly.
$ System=('s1' 's2' 's3' 's4 4 4') $ var=$( IFS=$'\n'; echo "${System[*]}" ) $ echo -e $var s1 s2 s3 s4 4 4 But when I include it verbatim in a function within a library, however, it does exactly what my own array was doing, and prints ...
s1 s2 s3 s4 4 4 On the command line piping to od confirms the use of the delimiter '\n'
$ echo -e $var | od -ab 0000000 s 1 nl s 2 nl s 3 nl s 4 sp 4 sp 4 nl 163 061 012 163 062 012 163 063 012 163 064 040 064 040 064 012 s 1 \n s 2 \n s 3 \n s 4 4 4 \n 0000020 From within the function the exact same statements insert a space as a delimiter '\s'
0000000 s 1 sp s 2 sp s 3 sp s 4 sp 4 sp 4 nl 163 061 040 163 062 040 163 063 040 163 064 040 064 040 064 012 s 1 s 2 s 3 s 4 4 4 \n 0000020 This has me stumped. How can I force the use of the '\n' delimiter within the function?
ADDITION TO QUESTION to illustrate the solution offered, which I have used. On the command line the quotes make no difference (which mislead me!); either echo -e $var or echo -e "$var" yield the correct output as below.
s1 s2 s3 s4 4 4 Within the script, the quotes do make a difference! Without quotes the delimiter is space (sp/040)
echo -e $var | od -abc 0000000 s 1 sp s 2 sp s 3 sp s 4 sp 4 sp 4 nl 163 061 040 163 062 040 163 063 040 163 064 040 064 040 064 012 s 1 s 2 s 3 s 4 4 4 \n 0000020 Within the script, with quotes the delimiter is newline (nl, 012,\n).
echo -e "$var" | od -abc 0000000 s 1 nl s 2 nl s 3 nl s 4 sp 4 sp 4 nl 163 061 012 163 062 012 163 063 012 163 064 040 064 040 064 012 s 1 \n s 2 \n s 3 \n s 4 4 4 \n 0000020 Thanks for this learning experience & is there a simple explanation for why the command line and the script behave differently?