bash print array elements on separate lines

匿名 (未验证) 提交于 2019-12-03 01:58:03

问题:

How do I print the array element of a Bash array on separate lines? This one works, but surely there is a better way:

$ my_array=(one two three) $ for i in ${my_array[@]}; do echo $i; done one two three 

Tried this one but it did not work:

$ IFS=$'\n' echo ${my_array[*]} one two three 

回答1:

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!



回答2:

Just quote the argument to echo:

( IFS=$'\n'; echo "${my_array[*]}" ) 

the sub shell helps restoring the IFS after use



回答3:

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[@]}" 


回答4:

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.



回答5:

Another useful variant is pipe to tr:

echo ${my_array[@]} | tr " " "\n"

This looks simple and compact



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!