NOTE: originally posted on 05 Sept 2014 more
What's up with shebang.
The shebang line is added at the top of a script to specify the path to the interpreter that should be used to run the script. The syntax of the shebang line would be like this:
For example, let's take a perl file test.pl
#!/usr/bin/perl use strict; use warnings; my $str = "Hello"; my $btr = "world"; print "\n$str $btr\n";
If we run this file(assuming the perl path is same is in your machine) directly ./test.pl, the perl interpreter inside /usr/bin/ would be called with the argument /path/to/test.pl
Let's play around with it a bit, try moving the shebang line to the second line of your code and run test.pl. You will get an error, which means shebang line should always be the first line of the script. You must be wondering why, it's because the Kernel will only look at the first 2 bytes at the start of the executable file, and if these are #! then the rest of the line is considered as the interpreter which will run our script. If all else fails then the kernel will try to execute the file as a shell script.
Next add some spaces between #! and the /path/to/interpreter, the program will run fine, spaces are allowed between #! and interpreter.
On one source I read a bit about space being mandatory after #! on some older versions on UNIX, but the post also says that it's 'virtually impossible to find a Unix which actually required this' :/ . I'll leave the links at the end if you want to know more about it.
Now give a wrong path and see what happens #!/usr/bah/humbub/, you will get an error 'bad interpreter'.
Is shebang line mandatory? nope. You can simply execute the file like this perl testfile.pl.
In fact there are some posts which say that it's better not to rely on it. Why? Portability. Say you wrote the perl script on your machine which has bath /alpha/beta/ then you copied it to another machine which has path /gamma/delta/ , the script breaks.
If you have the shebang line and you are calling the script with perl, then the line will simply be ignored, so it doesn't hurt to have it there.
A few tips to end the whole shebang,
Find the locations of perl in your system with this command:
To know which perl is getting execute when you run perl test.pl use any of these commands
which perl or
perl -le 'print $^X'
There's a lot more to read about #!, take a look through these links if you have time time.