Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does a script prefaced with #!/bin/rm delete itself?

I was reading 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.

Usually rm takes an argument and deletes that file. Here, rm somehow knows to act upon the script it's executing. Does that mean that when a shell encounters the #!, it passes the (fully qualified?) path to that file as the argument to the program specified after #!?

like image 968
Dmitry Minkovsky Avatar asked Sep 05 '13 05:09

Dmitry Minkovsky


2 Answers

Suppose the name of your script file is foo, and it begins with the shebang:

#!/bin/sh 

It's as if when you run the script, it's like you run it like:

/bin/sh foo

In your example, the shebang is:

#!/bin/rm

So it's as if run the script like:

/bin/rm foo

which in result deletes itself.

like image 97
Yu Hao Avatar answered Sep 21 '22 01:09

Yu Hao


Yes, you're exactly right when you say "it passes the (fully qualified?) path to that file as the argument to the program specified after #!".

This is why shell scripts start with #!/bin/sh or similar, and Python scripts start with something like #!/usr/local/bin/python.

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

like image 25
RichieHindle Avatar answered Sep 21 '22 01:09

RichieHindle