Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does OSX require shebang interpreters to be binaries?

Tags:

bash

shell

macos

Referencing the answer to this question, When writing a haskell script, get syntax error near unexpected token.

It turns out that when writing a script and telling bash on Mac OS X Mavericks to run it with a certain interpreter like so: #!/usr/local/bin/myinterpreter will fail if myinterpreter is also a shell script. However this works fine on Debian and ArchLinux. What is the difference in implementations that causes this to happen, and why did Apple implement it as such? Was there a tradeoff made here, or is this just a bug?

like image 603
Ramith Jayatilleka Avatar asked Oct 30 '25 07:10

Ramith Jayatilleka


1 Answers

See this page for all sorts of information about shebang lines.

For this question this section is the relevant one:

interpreter itself as #! script
or: can you nest #!?

Most probably there isn't any Bell-Labs- or Berkeley-derived Unix that accepts the interpreter to be a script, which starts with #! again. 
However, Linux since 2.6.27.9[2] and Minix accept this.

Be careful not to confuse whether the kernel accepts it, or if the kernel has returned with an ENOEXEC 
and your shell silently tries to take over, parsing the #! line itself.

- bash-1 behaves so (the line length then is truncated to 80 characters and argv[0] becomes the invoked script.)
- bash-2, -3 and -4 do so, if the #! mechanism was not present at compile time (probably only in unix-like environments like cygwin).
- The original Almquist shell also recognizes #!, but only if "BSD" was not defined at compile time. Later variants de-facto do not recognize it.
- If a filesystem is mounted with a "noexec" option, the shell might take over as well (pointed out by Carl Lowenstein).

[2] For more information about nested #! on Linux, see the kernel patch (applied to 2.6.27.9) and especially binfmt_script.c which contains the important parts. 
Linux allows at most BINPRM_MAX_RECURSION, that is 4, levels of nesting. 
(hint to me about the change by Mantas Mikulėnas.)
like image 70
Etan Reisner Avatar answered Oct 31 '25 22:10

Etan Reisner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!