首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >哪种语言出现在脚本的第一行?

问哪种语言出现在脚本的第一行?
EN

Unix & Linux用户
提问于 2013-11-06 00:04:48
回答 2查看 507关注 0票数 3

Bash脚本以以下行开始

代码语言:javascript
复制
#!/bin/bash
# Rest of script below
...

在bash中,#字符是注释的开始,但是#!/bin/bash绝对不是注释,因此解释该语句的它不是bash,而是内核。

那第一行到底是什么?它是一种特定的语言,还是Linux内核中的一种特殊的一次性情况?在这种“语言”中还有其他命令或语句可以在脚本编写时使用吗?

EN

回答 2

Unix & Linux用户

发布于 2013-11-06 00:21:21

就像Ignacio说的,对操作系统中的程序加载程序来说,这其实有点神奇。当用户试图执行程序时,加载程序读取程序的前两个字节来学习{something}。如果这两个字节恰好是#和!,内核将读取从字节3到第一个换行符的所有内容(在许多系统中它是换行符)。它使用它找到的字符串作为路径名,然后,如果它可以执行路径名上的任何内容,它会将第一个程序文件的其余部分作为输入提供给该可执行文件。

那些想要一个更精妙的解释的人可以在谷歌上搜索“她的内核魔法”,并在http://en.wikipedia.org/wiki/Shebang_(Unix)上跟随维基百科条目的链接。

票数 2
EN

Unix & Linux用户

发布于 2013-11-06 00:21:37

谢邦(#!)就是所谓的幻数。#!是两个字节0x23和0x21的可读形式。如果您看到C函数的手册页,execve(),这些exec函数的家族,在这些字节上出现了什么,并且在出现时会有不同的行为。

从execve()手册页摘录

代码语言:javascript
复制
DESCRIPTION
       execve()  executes the program pointed to by filename.  filename must be 
       either a binary executable, or a script starting with a line of the form:

           #! interpreter [optional-arg]

       For details of the latter case, see "Interpreter scripts" below.

       argv is an array of argument strings passed to the new program.  envp is 
       an array of strings, conventionally of the  form key=value,  which are 
       passed as environment to the new program.  Both argv and envp must be 
       terminated by a null pointer. The argument vector and environment can be 
       accessed by the called program's main function, when it is defined as:

           int main(int argc, char *argv[], char *envp[])

       execve() does not return on success, and the text, data, bss, and stack 
       of the calling process are overwritten by that of the program loaded.

       If the current program is being ptraced, a SIGTRAP is sent to it after a
       successful execve().

敏锐的眼睛会注意到,她的形式只需要两个论点。一个是解释器,另一个是[optional-arg]。这就是为什么您不能传递超过一个参数,至少在Linux上。

所以这样的命令不能工作,我相信-f被忽略了。

代码语言:javascript
复制
#!/usr/bin/foo -i -f

但是,如果解释器支持它,您可以通过这样做在一定程度上绕过这个限制:

代码语言:javascript
复制
#!/usr/bin/foo -if
票数 2
EN
页面原文内容由Unix & Linux提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://unix.stackexchange.com/questions/98993

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档