【问题标题】:What happens if the interpreter specified after #! is not available?如果解释器在#! 之后指定,会发生什么情况?不可用?
【发布时间】:2022-01-21 05:25:55
【问题描述】:

如果#! 之后指定的解释器不可用会怎样?

我知道在 shebang 之后我必须指定解释器(最佳做法是 /bin/bash)。新手不敢多尝试,怕损坏系统。

能否给我两个场景的截图示例:

  • 解释器存在
  • 解释器不可用

我只是想明白。

【问题讨论】:

  • 试一试。你不会损坏任何东西,保证。
  • 好的,谢谢。所以我将首先尝试使用可用的解释器,但我怎么知道我的系统中没有哪个解释器......对不起,我是一个真正的初学者:)
  • 当然,输入一些垃圾。 #!/foo/bar#!blahdeblah 或其他。
  • 我收到了这个'#!' is not recognized as an internal or external command, operable program or batch file.
  • 对于什么用作 shebang 没有最佳实践。使用执行正确解释器所需的任何路径。 (注意,这意味着 安装程序 处于选择使用哪个路径的最佳位置,而不是脚本的作者。)

标签: linux shell shebang


【解决方案1】:

多试几次恐怕会损坏我的系统。

别担心 - 这里很安全。程序员总是打错字。

解释器存在

例如,名为thefile 的文件包含以下内容:

#!/bin/cat
blabla

然后,当文件有executable permission bit set 时,executing 文件本身将执行带有一个参数./thefile 的程序/bin/cat,就像您在shell 中键入/bin/cat ./thefile 一样。 Program cat 只是打印文件的内容,所以在执行./thefile 时会执行/bin/cat ./thefile with 会将文件内容打印到屏幕上。

$ ./thefile 
#!/bin/cat
blabla

解释器不可用

如果解释器在#! 之后指定会发生什么?不可用?

如果 shebang 恰好被您的 shell 解释,那么预计您的 shell 将打印某种信息消息,它无法找到解释器,并带有一些错误描述“此文件确实不存在”或类似的。如果文件通过one of exec*()system calls 运行,则kernel 将返回ENOEXEC error code(根据source code here

让我们获取一个名为anotherfile 的文件,其内容如下:

#!fdsafdsafafdasfdas
blabla

例如,Bash shell will try to parse #! line 本身。 Bash 交互式 shell 将打印:

$ ./anotherfile 
bash: ./anotherfile: fdsafdsafafdasfdas: bad interpreter: No such file or directory

但是,例如 Busybox 的 Ash shell presents a different message

$ ./anotherfile 
/bin/sh: ./anotherfile: not found

https://en.wikipedia.org/wiki/Shebang_(Unix) 也可能很有趣。

【讨论】: