为什么在变量中循环遍历字符串是不同的

ant*_*ell 4 bash shell-script

我想知道为什么当你迭代一个变量时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
Run Code Online (Sandbox Code Playgroud)

但是,如果您不先将字符串放入变量中,则会得到完全不同的行为:

$ for a in "1 2 3"; do echo $a $a $a; done
1 2 3 1 2 3 1 2 3
Run Code Online (Sandbox Code Playgroud)

或陌生人:

$ for a in ""1 2 3""; do echo $a $a $a; done
1 1 1
2 2 2
3 3 3
Run Code Online (Sandbox Code Playgroud)

如果字符串是否在变量中,为什么它的行为会有所不同?

Dop*_*oti 7

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
Run Code Online (Sandbox Code Playgroud)