Self deleting bash script

落爺英雄遲暮 提交于 2019-12-10 01:11:54

问题


How can a bash script execute even after encountering a statement to delete itself? For eg when I ran test.sh script which conains:

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

end

The script executes till the end before deleting itself


回答1:


What actually happens is that bash keeps the file open and rm won't make that stop.

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).

The inode exists for as long as programs have it open.

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.




回答2:


In fact, this phenomenon is specific to shells (like bash), which read the file into memory and then execute them.

If you execute the following a.bat: echo Yo1 del a.bat echo Yo2

You get the following output: C:>a.bat

C:>echo Yo1 Yo1

C:>del a.bat The batch file cannot be found.

This is per your expectation :-)



来源:https://stackoverflow.com/questions/7834667/self-deleting-bash-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!