Shebang line in shell scriptI have simple perl script as below:
#!/usr/bin/perl use strict; use warnings; print "hello ! world\n";
I can execute this script as below:
>temp.pl hello ! world >
if i add some comments like this:
#this script is just for test
print "hello ! world\n";
> temp.pl use: Command not found. use: Command not found. print: Command not found. >
What wiki says?
In computing, a shebang (also called a sha-bang,hashbang,pound-bang,hash-exclam,or hash-pling) is the character sequence consisting of the characters number sign and exclamation mark (that is, "#!") when it occurs as the initial two characters on the initial line of a script.
Under Unix-like operating systems, when a script with a shebang is run as a program, the program loader parses the rest of the script's initial line as an interpreter directive; the specified interpreter program is run instead, passing to it as an argument the path that was initially used when attempting to run the script. For example, if a script is named with the path "path/to/script", and it starts with the following line:
Why should it always be the first line?
The shebang must be the first line because it is interpreted by the kernel, which looks at the two bytes at the start of an executable file. If these are
#!the rest of the line is interpreted as the executable to run and with the script file available to that program on stdin. (Details vary slightly, but that is the picture).
Since the kernel will only look at the first two characters and has no notion of further lines, you must place the hash bang in line 1.
Now what happens if the kernel can't execute a file beginning with
#whatever? The shell, attempting to fork an executable and being informed by the kernel that it can't execute the program, as a last resort attempts to interpret the file contents as a shell script. Since the shell is not perl, you get a bunch of errors, exactly the same as if you attempted to run