自删除bash脚本 [英] Self deleting bash script

查看:171
本文介绍了自删除bash脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何bash脚本,即使遇到语句删除自身后执行的?
对于例如,当我跑test.sh脚本conains:

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

推荐答案

什么真正发生的是bash的保持文件打开和 RM 不会犯停止。

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

所以 RM 调用的libc功能的unlink(),这将删除链接,从它在目录中的i节点。这种链接实际上是在有一个inode编号的文件名一起(你可以看到inode编号与 LS -i )。

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

inode的存在,只要程序有它打开。

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

即使你不再能看到它在LS文件仍然打开。
所以它不是bash的读取整个文件 - 这根本不是真的消失了,直到bash以它做

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.

这篇关于自删除bash脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆