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
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Rontonco
  • 23
  • 4

1 Answers1

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.

armandino
  • 17,625
  • 17
  • 69
  • 81
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • 1
    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. – Gordon Davisson Nov 20 '19 at 16:46