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

查看:32
本文介绍了在 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

试过这个,但没有用:

$ 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天全站免登陆