为什么shebang行总是第一行? [英] Why should the shebang line always be the first line?

查看:43
本文介绍了为什么shebang行总是第一行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的 perl 脚本,如下所示:

I have a simple perl script as below:

#!/usr/bin/perl

use strict;
use warnings;

print "hello world!
";

我可以如下执行这个脚本:

I can execute this script as below:

>temp.pl
hello world!
>

如果我添加一些这样的评论:

If I add some comments like this:

#this script is just for test
#the shebang
#!/usr/bin/perl

use strict;
use warnings;

print "hello world!
";

当我尝试执行时,它给了我如下输出:

and when I try to execute, it gives me output as below:

> temp.pl
use: Command not found.
use: Command not found.
print: Command not found.
> 

这里的重点是,无论如何,shebang 线应该始终位于顶部.谁能解释一下为什么?

The point here is the shebang line should be always at the top, no matter what. Can anybody explain why?

推荐答案

shebang 必须在第一行,因为它是由 kernel 解释的,它查看一个开头的两个字节可执行文件.如果这些是 #!,则该行的其余部分将被解释为要运行的可执行文件以及该程序可用的脚本文件.(细节略有不同,但这就是图片).

The shebang must be the first line because it is interpreted by the kernel, which looks at the two bytes at the start of an executable file. If these are #! the rest of the line is interpreted as the executable to run and with the script file available to that program. (Details vary slightly, but that is the picture).

由于内核只会查看前两个字符而没有其他行的概念,因此您必须将哈希爆炸放在第 1 行.

Since the kernel will only look at the first two characters and has no notion of further lines, you must place the hash bang in line 1.

现在如果内核不能执行以#!whatever 开头的文件怎么办?外壳程序试图派生一个可执行文件并被内核通知它无法执行程序,作为最后的手段,它试图将文件内容解释为外壳程序脚本.由于 shell 不是 perl,你会得到一堆错误,就像你试图运行一样

Now what happens if the kernel can't execute a file beginning with #!whatever? The shell, attempting to fork an executable and being informed by the kernel that it can't execute the program, as a last resort attempts to interpret the file contents as a shell script. Since the shell is not perl, you get a bunch of errors, exactly the same as if you attempted to run

 sh temp.pl

这篇关于为什么shebang行总是第一行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆