Bash – Why doesn’t the separator from IFS work for array expansion

arraybash

I want to limit the change to the separator only to the following echo command not to the shell:

$ myarr=(1 2 3)

$ echo $( IFS="|"; echo "${myarr[@]}" )
1 2 3

Why doesn't the separator work for array expansion? Thanks.

Best Answer

From POSIX, regarding $*:

When the expansion occurs in a context where field splitting will not be performed, the initial fields shall be joined to form a single field with the value of each parameter separated by the first character of the IFS variable if IFS contains at least one character, or separated by a <space> if IFS is unset, or with no separation if IFS is set to a null string.

To join words with a separator, you will have to use $*, or ${array[*]} in bash:

$ set -- word1 word2 word3 "some other thing" word4
$ IFS='|'
$ echo "$*"
word1|word2|word3|some other thing|word4

Or, with an array in bash:

$ arr=( word1 word2 word3 "some other thing" word4 )
$ IFS='|'
$ echo "${arr[*]}"
word1|word2|word3|some other thing|word4

With your code:

$ myarr=( 1 2 3 )
$ echo "$( IFS="|"; echo "${myarr[*]}" )"
1|2|3
Related Question