Print array elements on separate lines in Bash?

ArraysBash

Arrays Problem Overview


How do I print the array element of a Bash array on separate lines? This one works, but surely there is a better way:

$ my_array=(one two three)
$ for i in ${my_array[@]}; do echo $i; done
one
two
three

Tried this one but it did not work:

$ IFS=$'\n' echo ${my_array[*]}
one two three

Arrays Solutions


Solution 1 - Arrays

Try doing this :

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

The difference between $@ and $*:

  • Unquoted, the results are unspecified. In Bash, both expand to separate args and then wordsplit and globbed.

  • Quoted, "$@" expands each element as a separate argument, while "$*" expands to the args merged into one argument: "$1c$2c..." (where c is the first char of IFS).

You almost always want "$@". Same goes for "${arr[@]}".

Always quote them!

Solution 2 - Arrays

Just quote the argument to echo:

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

the sub shell helps restoring the IFS after use

Solution 3 - Arrays

Using for:

for each in "${alpha[@]}"
do
  echo "$each"
done

Using history; note this will fail if your values contain !:

history -p "${alpha[@]}"

Using basename; note this will fail if your values contain /:

basename -a "${alpha[@]}"

Using shuf; note that results might not come out in order:

shuf -e "${alpha[@]}"

Solution 4 - Arrays

Another useful variant is pipe to tr:

echo "${my_array[@]}" | tr ' ' '\n'

This looks simple and compact

Solution 5 - Arrays

I tried the answers here in a giant for...if loop, but didn't get any joy - so I did it like this, maybe messy but did the job:

 # EXP_LIST2 is iterated    
 # imagine a for loop
     EXP_LIST="List item"    
     EXP_LIST2="$EXP_LIST2 \n $EXP_LIST"
 done 
 echo -e $EXP_LIST2

although that added a space to the list, which is fine - I wanted it indented a bit. Also presume the "\n" could be printed in the original $EP_LIST.

Solution 6 - Arrays

You could use a Bash C Style For Loop to do what you want.

my_array=(one two three)

for ((i=0; i < ${#my_array[@]}; i++ )); do echo "${my_array[$i]}"; done
one
two
three

Solution 7 - Arrays

I've discovered that you can use eval to avoid using a subshell. Thus:

IFS=$'\n' eval 'echo "${my_array[*]}"'

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAxel BregnsboView Question on Stackoverflow
Solution 1 - ArraysGilles QuenotView Answer on Stackoverflow
Solution 2 - ArraysperrealView Answer on Stackoverflow
Solution 3 - ArraysZomboView Answer on Stackoverflow
Solution 4 - Arrays0x00View Answer on Stackoverflow
Solution 5 - ArrayswuxmediaView Answer on Stackoverflow
Solution 6 - ArraysDelyan LazarovView Answer on Stackoverflow
Solution 7 - ArraysMario NigrovicView Answer on Stackoverflow