codefx
codefx

Reputation: 10512

How does IFS replace char?

I thought that IFS is used to split strings into words in bash. How does this join function work? (source):

function join { local IFS="$1"; shift; echo "$*"; }

Example:

$ arr=( 1 a 2 b c d e 3 )
$ join , "${arr[@]}"
1,a,2,b,c,d,e,3

This seems to replace space with the first parameter passed to join.

Thanks.

Upvotes: 0

Views: 169

Answers (1)

that other guy
that other guy

Reputation: 123500

You are assuming that $* always joins with spaces. It actually joins on the first character of IFS.

Here's man bash which describes $* under "Special Parameters":

[...] When the expansion occurs within double quotes, it expands to a single word with the value of each parameter separated by the first character of the IFS special variable. That is, "$*" is equivalent to "$1c$2c...", where c is the first character of the value of the IFS variable. If IFS is unset, the parameters are separated by spaces. If IFS is null, the parameters are joined without intervening separators.

Upvotes: 4

Related Questions