How does the script preceding #! / Bin / rm itself get deleted?

I read Chapter 2 of the Advanced Bash-Scripting Guide , where I read about this script in a footnote :

#!/bin/rm # Self-deleting script. # Nothing much seems to happen when you run this... except that the file disappears. WHATEVER=85 echo "This line will never print (betcha!)." exit $WHATEVER # Doesn't matter. The script will not exit here. # Try an echo $? after script termination. # You'll get a 0, not a 85. 

Normally rm takes an argument and deletes this file. Here rm somehow knows how to proceed when executing the script. Does this mean that when the shell encounters #! , it passes the path (fully qualified?) to this file as an argument to the program specified after #! ?

+6
source share
4 answers

Yes, you are absolutely right when you say "it passes the path (fully qualified?) To this file as an argument to the program specified after #!".

That's why shell scripts start with #!/bin/sh or the like, and Python scripts start with #!/usr/local/bin/python .

The "shebang" line is intended to run the interpreter for scripts, but any executable file can be specified.

+3
source

Suppose your script file name is foo , and it starts with shebang:

 #!/bin/sh 

As if you were running a script, it seems to be running it, like:

 /bin/sh foo 

In your shebang example:

 #!/bin/rm 

So, as if running a script like:

 /bin/rm foo 

which as a result removes itself.

+3
source

When the script contains shebang and is executed, saying:

 ./path/to/script 

the program loader is prompted to run the path specified on the shebang line, specifying the path to the script as an argument.

In your case, the script contains #!/bin/rm as the first line and executes it by saying

 ./selfdeletingscript.sh 

will result in the following:

 /bin/rm ./selfdeletingscript.sh 

In addition, you may notice that the execution of your script:

 /bin/sh ./selfdeletingscript.sh 

or

 bash ./selfdeletingscript.sh 

will not delete it because you specified the path to the interpreter.

+2
source

Yes, bash executes the script as

 /bin/rm <Name of script file> [Optional arguments] 

From bash man page

If the program is a file starting with C # !, the remainder of the first line indicates the interpreter for the program. The shell executes the specified interpreter on operating systems that do not process this executable format, the self. Arguments for the interpreter consist of one optional argument following the name of the interpreter on the first line of the program, followed by the name of the program, followed by the arguments of the command, if any.

+1
source

Source: https://habr.com/ru/post/953209/


All Articles