在Bash中的不同行上打印数组元素? [英] Print array elements on separate lines in Bash?

查看:76
本文介绍了在Bash中的不同行上打印数组元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在单独的行上打印Bash数组的数组元素?此方法有效,但肯定有更好的方法:

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

推荐答案

尝试执行此操作:

$ printf '%s\n' "${my_array[@]}"

$@$*之间的区别:

  • 未引用,结果未指定.在Bash中,两者都扩展为单独的args 然后单词拆分和修饰.

  • Unquoted, the results are unspecified. In Bash, both expand to separate args and then wordsplit and globbed.

"$@"将每个元素扩展为单独的参数,而"$*" 扩展为合并到一个参数中的args:"$1c$2c..."(其中cIFS的第一个字符.

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).

您几乎总是想要"$@". "${arr[@]}"也是如此.

You almost always want "$@". Same goes for "${arr[@]}".

总是引用它们!

这篇关于在Bash中的不同行上打印数组元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆