简体   繁体   English

自我删除bash脚本

[英]Self deleting bash script

How can a bash script execute even after encountering a statement to delete itself? 即使在遇到要删除自身的语句之后,bash脚本如何执行? For eg when I ran test.sh script which conains: 例如,当我运行test.sh脚本时,该脚本具有以下特征:

<--some commands-->
rm test.sh
<--some more commands-->

end

The script executes till the end before deleting itself 脚本在删除之前执行到结束

What actually happens is that bash keeps the file open and rm won't make that stop. 实际发生的是bash保持文件打开, rm不会停止。

So rm calls 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号(你可以看到带有ls -i 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. 即使您无法再在ls中看到该文件,该文件仍会打开。 So it's not that bash read the whole file - it's just not really gone until bash is done with it. 所以不是bash读取整个文件 - 直到bash完成它才真正消失。

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:>回声Yo1 Yo1

C:>del a.bat The batch file cannot be found. C:> del a.bat找不到批处理文件。

This is per your expectation :-) 这是你的期望:-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM