Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl dispatches to other interpreters based on shebang line? [duplicate]

Tags:

shebang

perl

My mind was blown when I accidentally ran a bash script using perl and it... worked. Experimenting further, it seems perl reads a script's shebang and dispatches to the correct interpreter:

$ cat /tmp/ohhai.sh
#!/bin/bash
echo ohhai bash

$ perl /tmp/ohhai.sh
ohhai bash

$ cat /tmp/ohhai.py
#!/usr/bin/python2
print 'ohhai python'

$ perl /tmp/ohhai.py
ohhai python

$ cat /tmp/ohhai.groovy
#!/usr/bin/groovy
println 'ohhai groovy'

$ perl /tmp/ohhai.groovy
ohhai groovy

um... wut?

To make sure I'm not crazy, I tried doing this with other interpreters and confirmed this is just a perl-ism:

$ python /tmp/ohhai.sh
  File "/tmp/ohhai.sh", line 2
    echo ohhai bash
             ^
SyntaxError: invalid syntax

$ ruby /tmp/ohhai.sh
ruby: no Ruby script found in input (LoadError)

$ bash /tmp/ohhai.py
/tmp/ohhai.py: line 2: print: command not found

Is this documented somewhere? Is it a new thing/old thing? ... Why?

"Swiss-Army chainsaw" indeed.

like image 332
Dylan Cali Avatar asked Nov 01 '15 12:11

Dylan Cali


People also ask

What is the use of shebang line in Perl?

The shebang line is the path to the Perl binary, and allows programmers to invoke Perl scripts directly instead of passing the script filename as an argument to Perl itself.

What is #! In Perl?

The "#!" is a shell scripting command used to say that the file should be considered an executable file and that it should be executed using the specified interpreter. Typically, the Perl interpreter will be located in either "/usr/local/bin/" or "/usr/bin".

What is Perl shebang?

Shebang is slang often used in the computer Perl programming and other script files. The term shebang refers to the "#!" located at the top of many script files that point to the associated program's path. For example, in a Perl script, the complete line may look like the following: #!/usr/local/bin/perl.

What is the purpose of hashbang in Unix?

Brian explains that hashbang, prounounced "shabang" is a line that starts with the characters '#'! in a Bash script and that indicates how the bash file should run. For instance, the hashbang can indicate in what language a file should be interpreted.


1 Answers

This is an old thing documented in perldoc perlrun:

If the #! line does not contain the word "perl" nor the word "indir" the program named after the #! is executed instead of the Perl interpreter. This is slightly bizarre, but it helps people on machines that don't do #!, because they can tell a program that their SHELL is /usr/bin/perl, and Perl will then dispatch the program to the correct interpreter for them.

like image 94
melpomene Avatar answered Sep 26 '22 00:09

melpomene