I have a 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
#the shebang
#!/usr/bin/perl
use strict;
use warnings;
print "hello world!\n";
and when I try to execute, it gives me output as below:
> temp.pl
use: Command not found.
use: Command not found.
print: Command not found.
>
The point here is the shebang line should be always at the top, no matter what. Can anybody explain why?
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. (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
sh temp.pl