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
CodePudding user response:
You can make a for loop to print all the elements of your array.
# declare your array variable
declare -a myarr=("Life","is","good","when","you","learning")
# get length of an array
length=${#myarr[@]}
for (( j=0; j<${length}; j ));
do
printf "${myarr[$j]}\n"
done
CodePudding user response:
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