I have a simple Hello World perl script.
#!/usr/bin/perl
print 'Hello world.';
It works fine if I run it via perl <file_name>
, but it fails I run it via sh <file_name>
.
My understanding of the first line is that it invokes the perl shell (similar to #!/usr/bin/bash will invoke a bash shell). So what exeactly is the difference between the two commands?
I found this thread http://ubuntuforums.org/showthread.php?t=1133334 that states sh <file_name>
"In that case, you don't run Perl at all, but the shell, which will call the program 'print'." IF that's the case is the #! just being interpreted as a comment. If so, is it needed at all?
(I am aware that I can chmod +x the file and run it dirrectly, but I just want to know the difference between the two methods I was using)
Best Answer
If you execute a file directly
The shebang line will be searched for the interpreter to run it. If you run
perl
orsh
with an argument, they'll behave as documented: try to interpret the file as a script in Perl or shell, respectively.When you explicitly set the interpreter from the command line (such as
sh foo.pl
orperl foo.pl
), the shebang line is not used to determine the interpreter to run. It is parsed for possible options, (for example with a#!/usr/bin/perl -w
shebang, running the script asperl foo.pl
will enable the-w
flag) but it is not used to determine which program should interpret the script.So, running a perl script as
sh foo.pl
means your system will try to interpret it as ansh
script instead, despite the perl shebang line.