简体   繁体   English

打印字符串数组 - Shell 脚本

[英]Print array of strings - Shell Script

Dears,亲爱的,

Simple question, I have a shell variable with the following values,简单的问题,我有一个具有以下值的 shell 变量,

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这是我想要打印它的方式,另外,我需要处理一个循环,因为这些元素中的每一个都将传递给 function 来处理字符串

Expected Output预计 Output

Life \
is \
good \
when \
you \
learning

You can make a for loop to print all the elements of your array.您可以创建一个 for 循环来打印数组的所有元素。

# 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:数组文字在 shell 中声明如下:

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 (注意扩展周围的"double quotes" ):

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:如果声明数组时单个元素中有空格,则使用"double quotes"

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:请注意,这也会扩展 glob:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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