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

前端之家收集整理的这篇文章主要介绍了如何迭代包含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

猜你在找的Bash相关文章