码迷,mamicode.com
首页 > 其他好文 > 详细

Shebang(#!)[转]

时间:2019-02-17 20:48:15      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:htm   plain   nothing   执行文件   nbsp   get   context   denied   符号   

原博文

使用Linux或者unix系统的同学可能都对#!这个符号并不陌生,但是你真的了解它吗?

首先,这个符号(#!)的名称,叫做"Shebang"或者"Sha-bang"。

Linux执行文件时发现这个格式,会把!后的内容提取出来拼接在脚本文件或路径之前,当作实际执行的命令。

 

Shebang这个符号通常在Unix系统的脚本中第一行开头中写到,它指明了执行这个脚本文件的解释程序。

1. 如果脚本文件中没有#!这一行,那么它执行时会默认用当前Shell去解释这个脚本(即:$SHELL环境变量)。

2. 如果#!之后的解释程序是一个可执行文件,那么执行这个脚本时,它就会把文件名及其参数一起作为参数传给那个解释程序去执行。

3. 如果#!指定的解释程序没有可执行权限,则会报错“bad interpreter: Permission denied”。
    如果#!指定的解释程序不是一个可执行文件,那么指定的解释程序会被忽略,转而交给当前的SHELL去执行这个脚本。

4. 如果#!指定的解释程序不存在,那么会报错“bad interpreter: No such file or directory”。
    注意:#!之后的解释程序,需要写其绝对路径(如:#!/bin/bash),它是不会自动到$PATH中寻找解释器的。

5. 当然,如果你使用"bash test.sh"这样的命令来执行脚本,那么#!这一行将会被忽略掉,解释器当然是用命令行中显式指定的bash。

例如:test.sh

chmod a+x  test.sh

./test.sh   Jay  (运行之时,其实是 /bin/bash ./test.sh Jay)

结果为:

hello, world.
hello, Jay.

 

Some typical shebang lines:

  • #!/bin/sh – Execute the file using the Bourne shell, or a compatible shell, with path /bin/sh
  • #!/bin/bash – Execute the file using the Bash shell.
  • #!/bin/csh -f – Execute the file using csh, the C shell, or a compatible shell, and suppress the execution of the user’s .cshrc file on startup
  • #!/usr/bin/perl -T – Execute using Perl with the option for taint checks
  • #!/usr/bin/env python – Execute using Python by looking up the path to the Python interpreter automatically via env
  • #!/bin/false – Do nothing, but return a non-zero exit status, indicating failure. Used to prevent stand-alone execution of a script file intended for execution in a specific context, such as by the . command from sh/bash, source from csh/tcsh, or as a .profile, .cshrc, or .login file.

 

 

主要参考资料:

http://en.wikipedia.org/wiki/Shebang_(Unix)

http://people.csail.mit.edu/jaffer/Docupage/sharpbang.html

Shebang(#!)[转]

标签:htm   plain   nothing   执行文件   nbsp   get   context   denied   符号   

原文地址:https://www.cnblogs.com/dirge/p/10392346.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!