while、do、done bash 中的流程控制
谁能解释一下以下bash脚本的控制流程?
while IFS= read -r file
do
rm -rf "$file"
done < todelete.txt
据我了解,会发生这种情况:
IFS 不会被分配任何内容。 rm -rf 命令不会执行任何操作,因为它的参数变量 $file 为空/空/无。 然后,前两个步骤将无限期地重复。
显然情况并非如此,因为脚本按预期工作;它会删除 todelete.txt 中列出的所有文件。
我相信解释在于“done < todelete.txt”,但我不明白那里发生了什么。
Can anyone explain the control flow of the following bash script?
while IFS= read -r file
do
rm -rf "$file"
done < todelete.txt
From what I understand, this would happen:
IFS would be assigned nothing.
The rm -rf command would do nothing because its argument, the variable $file, is blank/empty/nothing.
The two previous steps would then repeat indefinitely.
Clearly this is not the case, because the script works as expected; it deletes all files listed in todelete.txt.
I believe the explanation lies in "done < todelete.txt" but I don't understand what's happening there.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
整个
while ... done
被视为单个命令,在其输入上提供一个todelete.txt
文件。while IFS= read -r file
事物从此输入文件中读取行,直到EOF
,将每一行分配给$file
变量,并且循环的每次迭代都会删除该文件。The whole
while ... done
is treated as single command, which is fed atodelete.txt
file on its input.The
while IFS= read -r file
thing reads the lines from this input file until theEOF
, assigning each line to$file
variable, and each iteration of the loop removes that file.done
后的重定向会影响read
的输入流。因此,read
将处理todelete.txt
的内容,而不是stdin
。您应该阅读 Bash 手册的内部命令部分以获取更多信息。 (直接浏览示例 15-7。)
The redirect after
done
affectsread
's input stream. Soread
will work on the contents oftodelete.txt
rather thanstdin
.You should read the Internal Commands section of the Bash manual for more info. (Browse directly to example 15-7.)