简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM