'Print array of strings - Shell Script

Dears,

Simple question, I have a shell variable with the following values,

myarr=["Life","is","good","when","you","learning"]

It is an array of strings ! Here is how I want to print it. Also, I need to do with a loop because each of these element would be passed to a function to process the string

Expected Output

Life \
is \
good \
when \
you \
learning


Solution 1:[1]

An array literal is declared in the shell like so:

myarr=(Life is good when you learning)

And if you have such an array you can pass it to printf like so (note the "double quotes" around the expansion):

printf "%s\n" "${myarr[@]}"
Life
is
good
when
you
learning

You use "double quotes" if you have spaces in individual elements when declaring the array:

myarr=("Life is good" when you learning)
printf "%s\n" "${myarr[@]}"
Life is good
when
you
learning

You can also just make a string value then NOT use quotes which will split the string:

mys="Life is good when you learning"
printf "%s\n" $mys
Life
is
good
when
you
learning

Beware though that that will also expand globs:

mys="Life is good when * you learning"
printf "%s\n" $mys
Life
is
good
when
...
a bunch of files from the glob in the cwd
...
file
you
learning

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1