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

Nik*_*e C 7 linux shell shebang

如果后面指定的解释器#!不可用怎么办?

我知道在 shebang 之后我必须指定解释器(最佳实践是/bin/bash)。作为一个初学者,我不敢尝试太多,因为我担心会损坏我的系统。

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

  • 解释器存在
  • 没有翻译员

我只是想了解一下。

Kam*_*Cuk 3

尝试很多,我担心会损坏我的系统。

别担心——这里很安全。程序员总是会犯错别字。

解释器存在

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

#!/bin/cat
blabla
Run Code Online (Sandbox Code Playgroud)

然后,当文件设置了可执行权限位时,执行文件本身将/bin/cat使用一个参数执行程序,就像您在 shell 中./thefile键入一样。程序只是打印文件的内容,因此在执行时将执行with 将文件内容打印到屏幕上。/bin/cat ./thefilecat./thefile/bin/cat ./thefile

$ ./thefile 
#!/bin/cat
blabla
Run Code Online (Sandbox Code Playgroud)

没有翻译员

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

如果 shebang 碰巧被您的shell解释,那么您的 shell 将打印某种信息消息,表明它找不到解释器,并带有一些错误描述“此文件不存在”或类似内容。如果该文件通过系统调用之一exec*() 运行,则内核将返回错误代码(根据此处的源代码ENOEXEC

anotherfile让我们使用以下内容命名的文件:

#!fdsafdsafafdasfdas
blabla
Run Code Online (Sandbox Code Playgroud)

例如,Bash shell会尝试#!自行解析行。Bash 交互式 shell 将打印:

$ ./anotherfile 
bash: ./anotherfile: fdsafdsafafdasfdas: bad interpreter: No such file or directory
Run Code Online (Sandbox Code Playgroud)

但是,例如,Busybox 的Ash shell会显示不同的消息

$ ./anotherfile 
/bin/sh: ./anotherfile: not found
Run Code Online (Sandbox Code Playgroud)

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