[英]Bash: Why does printf not respect newline char?
Why does this bash script (at bottom) not output the newline? 为什么这个bash脚本(在底部)不输出换行符? The result is: 结果是:
filesonetwothree
instead of 代替
files
one
two
three
Here's the script: 这是脚本:
files=()
files+="one"
files+="two"
files+="three"
printf "\nfiles"
for file in "${files[@]}"
do
printf "$file\n"
done
NOTE: This is on a Mac running macOS Sierra 注意:这是在运行macOS Sierra的Mac上
The following will make your issue very clear: 以下内容将使您的问题非常清楚:
files=()
files+="one"
files+="two"
files+="three"
declare -p files
...emits as output: ...作为输出发出:
declare -a files='([0]="onetwothree")'
...so, you were appending to the first element of the array , not adding new elements to the array's end. ...因此,您要追加到数组的第一个元素 ,而不是在数组的末尾添加新元素。
To correctly append to an array, use the following instead: 若要正确追加到数组,请改用以下内容:
files=()
files+=("one")
files+=("two")
files+=("three")
declare -p files
...which emits: ...发出:
declare -a files='([0]="one" [1]="two" [2]="three")'
In either case, to print your array one-line-to-an-element, use a format string with a newline, and pass your array elements as subsequent arguments: 在这两种情况下,要单行打印数组,请使用带换行符的格式字符串,并将数组元素作为后续参数传递:
printf '%s\n' "${files[@]}"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.