为什么OSX要求shebang解释器是二进制文件?

时间:2014-09-17 15:41:01

标签: macos bash shell

引用此问题的答案When writing a haskell script, get syntax error near unexpected token

事实证明,当编写脚本并告诉Mac OS X Mavericks上的bash使用某个解释器运行它时,如果#!/usr/local/bin/myinterpreter也是shell脚本,myinterpreter将会失败。然而,这在Debian和ArchLinux上运行良好。导致这种情况发生的实现有什么不同,为什么Apple会这样做呢?这里是否有权衡,或者这只是一个错误?

1 个答案:

答案 0 :(得分:2)

有关shebang line的各种信息,请参阅this page

对于这个问题this section是相关问题:

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.)