我想知道为什么当你迭代一个变量时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