如何迭代包含bash空格的列表

你能告诉我如何迭代列表中的项目可以包含空格吗?

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
要正确循环项目,您需要使用${var [@]}.并且您需要引用它以确保带有空格的项目不会被拆分:“${var [@]}”.

全部一起:

x=("some word" "other word" "third word")
for word in "${x[@]}" ; do
  echo -e "$word\n"
done

或者,saner(thanks Charles Duffy)与printf:

x=("some word" "other word" "third word")
for word in "${x[@]}" ; do
  printf '%s\n\n' "$word"
done
相关文章
相关标签/搜索