Print array elements on separate lines in Bash?
Just quote the argument to echo:
( IFS=$'\n'; echo "${my_array[*]}" )
the sub shell helps restoring the IFS after use
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[@]}"
Another useful variant is pipe to tr
:
echo "${my_array[@]}" | tr ' ' '\n'
This looks simple and compact
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..."
(wherec
is the first char ofIFS
).
You almost always want "$@"
. Same goes for "${arr[@]}"
.
Always quote them!