你能告诉我如何迭代列表中的项目可以包含空格吗?
x=("some word", "other word", "third word")
for word in $x ; do
echo -e "$word\n"
done
如何强制输出:
some word
other word
third word
而不是:
some
word
(...)
third
word
答案 0 :(得分:7)
要正确循环浏览项目,您需要使用${var[@]}
。并且您需要引用它以确保包含空格的项目不会被拆分:"${var[@]}"
。
所有在一起:
x=("some word" "other word" "third word")
for word in "${x[@]}" ; do
echo -e "$word\n"
done
或者,printf
与x=("some word" "other word" "third word")
for word in "${x[@]}" ; do
printf '%s\n\n' "$word"
done
:
{{1}}
答案 1 :(得分:2)
两种可能的解决方案,一种类似于fedorqui的解决方案,没有额外的',',另一种使用数组索引:
x=( 'some word' 'other word' 'third word')
# Use array indexing
let len=${#x[@]}-1
for i in $(seq 0 $len); do
echo -e "${x[i]}"
done
# Use array expansion
for word in "${x[@]}" ; do
echo -e "$word"
done
输出:
some word
other word
third word
some word
other word
third word
修改修复了cravoori指出的索引解决方案的问题