bash 自删除bash脚本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7834667/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Self deleting bash script
提问by user1004985
How can a bash script execute even after encountering a statement to delete itself? For eg when I ran test.sh script which conains:
即使遇到要删除自身的语句,bash 脚本如何执行?例如,当我运行包含以下内容的 test.sh 脚本时:
<--some commands-->
rm test.sh
<--some more commands-->
end
The script executes till the end before deleting itself
脚本执行到结束,然后删除自身
回答by w00t
What actually happens is that bash keeps the file open and rmwon't make that stop.
实际发生的是 bash 保持文件打开并且rm不会停止。
So rmcalls the libc function "unlink()" which will remove the "link" to the inode from the directory it's in. This "link" is in fact a filename together with an inode number (you can see inode numbers with ls -i).
所以rm调用 libc 函数“unlink()”,它将从它所在的目录中删除到 inode 的“链接”。这个“链接”实际上是一个文件名和一个 inode 编号(你可以看到 inode 编号ls -i)。
The inode exists for as long as programs have it open.
只要程序打开,inode 就会一直存在。
You can easily test this claim as follows:
您可以按如下方式轻松测试此声明:
$ echo read a> ni
$ bash ni
while in another window:
而在另一个窗口中:
$ pgrep -lf bash\ ni
31662 bash ni
$ lsof -p 31662|grep ni
bash 31662 wmertens 255r REG 14,2 7 12074052 /Users/wmertens/ni
$ rm ni
$ lsof -p 31662|grep ni
bash 31662 wmertens 255r REG 14,2 7 12074052 /Users/wmertens/ni
The file is still opened even though you can no longer see it in ls. So it's not that bash read the whole file - it's just not really gone until bash is done with it.
即使您不再能在 ls 中看到该文件,该文件仍处于打开状态。所以并不是说 bash 读取了整个文件 - 在 bash 完成它之前它并没有真正消失。
回答by savinderpuri
In fact, this phenomenon is specific to shells (like bash), which read the file into memory and then execute them.
事实上,这种现象是特定于 shell(如 bash)的,它会将文件读入内存然后执行它们。
If you execute the following a.bat: echo Yo1 del a.bat echo Yo2
如果执行以下a.bat:echo Yo1 del a.bat echo Yo2
You get the following output: C:>a.bat
你得到以下输出:C:>a.bat
C:>echo Yo1 Yo1
C:>echo Yo1 Yo1
C:>del a.bat The batch file cannot be found.
C:>del a.bat 找不到批处理文件。
This is per your expectation :-)
这是根据您的期望:-)

