前端之家收集整理的这篇文章主要介绍了
我应该使用带Bash脚本的Shebang吗?,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_
502_0@
我正在使用Bash
$ echo $SHELL
/bin/bash
从大约一年前开始,我停止使用Shebangs和我的Bash脚本。能够
我使用#!/ bin / sh或#!/ bin / bash受益?
更新:在某些情况下,文件仅被视为带有的脚本
Shebang,例子
$ cat foo.sh
ls
$ cat bar.sh
#!/bin/sh
ls
$ file foo.sh bar.sh
foo.sh: ASCII text
bar.sh: POSIX shell script,ASCII text executable
在类UNIX系统上,您应该始终使用shebang行启动脚本。系统
调用execve(负责启动程序)依赖于具有可执行标头或shebang线的可执行
文件。
来自FreeBSD的execve manual page:
06000
同样来自Linux manual page:
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:
06001
事实上,如果一个文件的标题中没有正确的“幻数”(如ELF标题或#!),execve将因ENOEXEC错误而失败(再次来自FreeBSD的execve联机帮助页):
[ENOEXEC] The new process file has the appropriate access
permission,but has an invalid magic number in its
header.
如果文件具有可执行权限,但没有shebang行但似乎确实是文本文件,则行为取决于您正在运行的shell。
大多数shell似乎开始自己的新实例并将其提供给文件,见下文。
由于无法保证脚本实际上是为该shell编写的,因此这可能会起作用或失败。
从tcsh(1):
06002
来自FreeBSD的sh(1):
If the program is not a normal executable file (i.e.,if it
does not begin with the “magic number” whose ASCII representation is
“#!”,resulting in an ENOEXEC return value from execve(2)) but appears to
be a text file,the shell will run a new instance of sh to interpret it.
来自bash(1):
06004
您不能总是依赖于像bash这样的非标准程序的位置。我在/ usr / bin,/usr/local/bin,/ opt / fsf / bin和/ opt / gnu / bin中看过bash等等。
所以使用env通常是个好主意;
#!/usr/bin/env bash
如果您希望脚本可移植,请使用sh而不是bash。
#!/bin/sh
虽然像POSIX这样的标准不能保证标准实用程序的绝对路径,但大多数类UNIX系统似乎都在/ usr / bin中使用/ bin和env。