To print each word on a new line, we need to use the keys “%s'\n”. '%s' is to read the string till the end. At the same time, '\n' moves the words to the next line. To display the content of the array, we will not use the “#” sign.
Print Bash Array We can use the keyword 'declare' with a '-p' option to print all the elements of a Bash Array with all the indexes and details. The syntax to print the Bash Array can be defined as: declare -p ARRAY_NAME.
How to Echo a Bash Array? To echo an array, use the format echo ${Array[0]}. Array is your array name, and 0 is the index or the key if you are echoing an associative array. You can also use @ or * symbols instead of an index to print the entire array.
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!
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With