加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

我应该使用带Bash脚本的Shebang吗?

发布时间:2020-12-15 19:05:47 所属栏目:安全 来源:网络整理
导读:我正在使用Bash $ echo $SHELL/bin/bash 从大约一年前开始,我停止使用Shebangs和我的Bash脚本。能够 我使用#!/ bin / sh或#!/ bin / bash受益? 更新:在某些情况下,文件仅被视为带有的脚本 Shebang,例子 $ cat foo.shls$ cat bar.sh#!/bin/shls$ file
我正在使用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。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读