6

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

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
4

2 回答 2

7

要正确循环项目,您需要使用${var[@]}. 并且您需要引用它以确保带有空格的项目不会被拆分:"${var[@]}"

全部一起:

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

或者,更理智(感谢 Charles Duffyprintf

x=("some word" "other word" "third word")
for word in "${x[@]}" ; do
  printf '%s\n\n' "$word"
done
于 2013-01-29T17:04:50.193 回答
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指出的索引解决方案的问题

于 2013-01-29T17:25:31.657 回答