Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Self deleting bash script

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

like image 292
user1004985 Avatar asked Oct 20 '11 10:10

user1004985


People also ask

Can bash script delete itself?

The file name will no longer exist, but the data itself does remain, and any programs that have an open handle, including bash, can continue to read (and even write) using that handle. Only when the last program closes its handle does the file really get deleted.

How do you delete a bash script?

To delete a specific file, you can use the command rm followed by the name of the file you want to delete (e.g. rm filename ). For example, you can delete the addresses. txt file under the home directory.

How do you terminate a shell script?

To end a shell script and set its exit status, use the exit command. Give exit the exit status that your script should have. If it has no explicit status, it will exit with the status of the last command run.

How do I stop a bash script execution?

If you are executing a Bash script in your terminal and need to stop it before it exits on its own, you can use the Ctrl + C combination on your keyboard.


1 Answers

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.

like image 128
w00t Avatar answered Oct 21 '22 09:10

w00t