我应该使用带Bash脚本的Shebang吗?
我正在使用Bash
$ echo $SHELL /bin/bash 从大约一年前开始,我停止使用Shebangs和我的Bash脚本。能够 更新:在某些情况下,文件仅被视为带有的脚本 $ 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:
同样来自Linux manual page:
事实上,如果一个文件的标题中没有正确的“幻数”(如ELF标题或#!),execve将因ENOEXEC错误而失败(再次来自FreeBSD的execve联机帮助页):
如果文件具有可执行权限,但没有shebang行但似乎确实是文本文件,则行为取决于您正在运行的shell。 大多数shell似乎开始自己的新实例并将其提供给文件,见下文。 由于无法保证脚本实际上是为该shell编写的,因此这可能会起作用或失败。 从tcsh(1):
来自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):
您不能总是依赖于像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。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |