2

How can I control how an array separates its elements? If you do:

echo ${array[*]}

it displays:

element1 element2 element3

and I would like it to be:

element1:element2:element3
0

1 Answer 1

4

Elements are joined by the first character of $IFS (internal field separator).

(IFS=':'; echo "${array[*]}")

Modifying $IFS has a lot of side effects. I recommend only changing it for a short duration inside a subshell so the rest of your script isn't affected.

Sign up to request clarification or add additional context in comments.

1 Comment

Note that the double-quotes around ${array[*]} are required for this to work right. Without them, it would join the elements with colons, then immediately re-split them (based on colons, 'cause that's in $IFS and word-splitting is what happens to unquoted variable references). The re-splitting completely reverses the joining operation (and might also split any elements that contain colon). It then passes the re-split elements to echo, which re-joins them, but with spaces this time (because echo doesn't pay attention to $IFS). Always double-quote your variable references.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.