我有一个简单的 perl 脚本,如下所示:
#!/usr/bin/perl
use strict;
use warnings;
print "hello world!\n";
我可以执行这个脚本如下:
>temp.pl
hello world!
>
如果我添加一些这样的评论:
#this script is just for test
#the shebang
#!/usr/bin/perl
use strict;
use warnings;
print "hello world!\n";
当我尝试执行时,它给了我如下输出:
> temp.pl
use: Command not found.
use: Command not found.
print: Command not found.
>
这里的重点是shebang线应该总是在顶部,无论如何。
任何人都可以解释为什么?
最佳答案
shebang 必须是第一行,因为它由 解释。内核 ,它查看可执行文件开头的两个字节。如果这些是 #!
该行的其余部分被解释为要运行的可执行文件以及该程序可用的脚本文件。 (细节略有不同,但这就是图片)。
由于内核只会查看前两个字符而没有其他行的概念,因此您必须将哈希爆炸放在第 1 行。
现在如果内核不能执行以 #!whatever
开头的文件会发生什么? shell 试图 fork 一个可执行文件并被内核通知它不能执行该程序,作为最后的手段,它试图将文件内容解释为一个 shell 脚本。由于 shell 不是 perl,你会得到一堆错误,就像你试图运行一样
sh temp.pl
关于perl - 为什么shebang行总是第一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12910744/