7

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.

Dylan Cali
  • 1,463
  • 1
  • 13
  • 17

1 Answers1

10

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.

melpomene
  • 84,125
  • 8
  • 85
  • 148