[英]Bash - Why do these two commands in a loop run in succession rather than parallel?
I'm trying to pick up some bash, and I can't figure out the following behavior. 我正试图拿起一些bash,我无法弄清楚以下行为。 I have a for loop, and it seems like one command is running through the whole loop before the other command starts even though they're within the same do
and done
structure. 我有一个for循环,似乎一个命令在另一个命令启动之前运行整个循环,即使它们在相同的do
和done
结构中。 See my example: 看我的例子:
Here's the shell script: 这是shell脚本:
for i in "$(ls .)"
do
printf "$i\n"
printf "$i\n"
done
If this was run in a directory with the files a
, b
, c
I would expect the output to be: 如果这是在包含文件a
, b
, c
的目录中运行a
,我希望输出为:
a
a
b
b
c
c
Instead it is: 相反,它是:
a
b
c
a
b
c
Can anyone explain to me what's going on? 任何人都可以向我解释发生了什么事吗?
Because you're expanding the expression in $(ls .)
before you pass it to the loop, it's evaluating all the files in the directory first and then printing it twice. 因为您在将表达式传递给循环之前将其扩展为$(ls .)
的表达式,所以它首先评估目录中的所有文件然后再打印两次。 In essence, your loop only contains one element which you print twice. 实质上,您的循环只包含一个您打印两次的元素。
The behaviour you want can be obtained by using the glob *
operator instead: 您可以通过使用glob *
运算符来获取所需的行为:
for i in *
do
printf "$i\n"
printf "$i\n"
done
This way *
represents a list to iterate over rather than a string that's already been evaluated. 这种方式*
表示迭代的列表,而不是已经被评估的字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.