![为什么当字符串位于变量中时,循环字符串会有所不同](https://linux22.com/image/88290/%E4%B8%BA%E4%BB%80%E4%B9%88%E5%BD%93%E5%AD%97%E7%AC%A6%E4%B8%B2%E4%BD%8D%E4%BA%8E%E5%8F%98%E9%87%8F%E4%B8%AD%E6%97%B6%EF%BC%8C%E5%BE%AA%E7%8E%AF%E5%AD%97%E7%AC%A6%E4%B8%B2%E4%BC%9A%E6%9C%89%E6%89%80%E4%B8%8D%E5%90%8C.png)
我想知道为什么当你迭代一个变量时n="1 2 3"
你会得到这个:
$ n="1 2 3"; for a in $n; do echo $a $a $a; done
1 1 1
2 2 2
3 3 3
但如果你不首先将字符串放入变量中,你会得到完全不同的行为:
$ for a in "1 2 3"; do echo $a $a $a; done
1 2 3 1 2 3 1 2 3
还是陌生人:
$ for a in ""1 2 3""; do echo $a $a $a; done
1 1 1
2 2 2
3 3 3
为什么如果字符串在变量中或不在变量中,它的行为会有所不同?
答案1
n="1 2 3"
for a in $n; do # This will iterate over three strings, '1', '2', and '3'
for a in "1 2 3"; do # This will iterate once with the single string '1 2 3'
for a in "$n"; do # This will do the same
for a in ""1 2 3""; do # This will iterate over three strings, '""1', '2', and '3""'.
# The first and third strings simply have a null string
# respectively prefixed and suffixed to them