views:

85

answers:

2

Does anyone know why the following script works?

#a-random-junk-string
echo HI

The shell executes the echo command, and outputs HI. I thought that since there is no "!" after the "#", the shell would give an error.

+12  A: 

If there is no #! specifying a specific interpreter, the kernel will not intercept and launch it with the specified program.

However, the current shell may still interpret it as a command file, which is what you are seeing take place.

Amardeep
This is correct. The reason the script still works is that '#' is the comment character in Bash/SH/ZSH/etc, so the first line is ignored as a comment.
Borealid
Thanks for the complete answer!
Yassin
+1  A: 

When the shell is asked to run a file with the executable bit turned on then it will examine the file and determine if it begins with a shebang #! if it does then it will execute that command which will get it's program text from the remainder of the file.

If the file does not start with a shebang then the shell will attempt to execute it itself. This is what is happening for you and the shell interprets the first line as a comment.

Steve Weet
Actually, the loader does this, not the shell. See http://www.in-ulm.de/~mascheck/various/shebang/sys1.c.html for Dennis Ritchie's announcement of this feature when it was added to Unix. It gives a wonderful explanation of why it's better for the loader to do it than for the shell to do it.
Dan Moulding
@Dan. Thanks that was interesting.
Steve Weet