Print BASH Array Elements on Separate Lines

Very easy and usually accomplished with a loop:

$ array=(red green blue)
$ for I in ${array[@]}; do echo $I; done

But we can do better!:

$ printf '%s\n' "${array[@]}"


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

Note the switch to "${array[*]}" from "${array[@]}" (the "quoting" is important!). Using [@] each element of the array is expanded into a separate quoted argument, while [*] expands to a single quoted argument of all elements -- with each element separated by the first character of the IFS variable (i.e. newlines in this case).

The above command also runs within a subshell so that IFS is restored after running the command. Also, the reason the value of IFS is a quoted \n starting with a $ is so bash expands the control sequence without dropping any trailing newlines (which command substitution does):

# expand control sequences without modification
$ echo -n $'\n' | od -c
0000000  \n

# with command substitution, no more \n
$ echo -n $(echo -ne '\n') | od -c