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

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

问题描述

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

I have a simple perl script as below:

#!/usr/bin/perl

use strict;
use warnings;

print "hello world!\n";

我可以如下执行该脚本:

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!\n";

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

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天全站免登陆