How to join an array in Bash
Say you want to build an array of values then print them out as a tab-separated line:
# Build an array.
row=(
"one"
"two"
"three"
)
# Set the internal field separator to the tab character.
IFS=$'\t';
# Echo the array.
echo "${row[*]}";
To understand how this works, consider the explanation of $*
from the Bash
Beginners Guide:
$*
Expands to the positional parameters, starting from one. 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.
In the above example we set IFS
to be a tab character using ksh93
syntax, then echo the array using $*
syntax which ensures the fields are
joined using a tab character.
Note that print arrays with *@
doesn’t have this behaviour:
$@
Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, each parameter expands to a separate word.