注:本文为 “Linux | Bash Shebang” 相关合辑。
英文引文,机翻未校。
如有内容异常,请看原文。
Unix Shebang and Shell Script Execution: History, Principles, and Engineering Practice
Unix Shebang 与 Shell 脚本执行:历史、原理与工程实践
1. Introduction
1. 引言
In Unix-like operating systems, the shebang (#!) mechanism enables text files containing scripts to be executed directly as commands. The operating system kernel parses the initial line of such files to determine the appropriate interpreter, which is then invoked to process the script contents. This mechanism allows scripts written in various languages to be executed without explicit interpreter invocation on the command line, and permits the implementation language of a script to be changed without altering its invocation syntax. Beyond the shebang itself, the robustness, portability, and security of shell scripts depend on adherence to POSIX standards, correct handling of pathnames, and awareness of interpreter-specific behaviors.
在类 Unix 操作系统中,shebang(#!)机制使包含脚本的文本文件能够作为命令直接执行。操作系统内核解析此类文件的初始行以确定相应的解释器,随后调用该解释器处理脚本内容。该机制允许使用多种语言编写的脚本在命令行上无需显式调用解释器即可执行,并允许在不改变调用语法的前提下更换脚本的实现语言。除 shebang 本身外,shell 脚本的健壮性、可移植性与安全性还取决于对 POSIX 标准的遵循、路径名的正确处理以及对解释器特定行为的认知。
2. Terminology and Definitions
2. 术语与定义
The character sequence #! is known by several names. The term shebang is a contraction of hash (or sharp) and bang, referring to the Unix slang names for # and !, respectively. Alternative names include hashbang, hash-pling, sha-bang, sharp-exclamation, and pound-bang. The sh prefix in shebang may also derive from the default Bourne shell sh, which is commonly invoked via this mechanism. An executable file starting with an interpreter directive is simply called a script. In the Unix shell ecosystem, Shell refers to the command interpreter, Bash is the GNU Bourne-Again Shell, Terminal denotes the GUI interaction interface, and TTY (teletypewriter) represents the underlying device abstraction for terminal sessions.
字符序列 #! 有多个名称。shebang 一词是 hash(或 sharp)与 bang 的缩合,分别指代 Unix 俚语中对 # 和 ! 的称呼。其他名称包括 hashbang、hash-pling、sha-bang、sharp-exclamation 和 pound-bang。shebang 中的前缀 sh 也可能来源于默认的 Bourne shell sh,该 shell 通常通过此机制调用。以解释器指令开头的可执行文件通常称为脚本。在 Unix shell 生态中,Shell 指命令解释器,Bash 指 GNU Bourne-Again Shell,Terminal 指图形交互界面,TTY(teletypewriter)指标签页对应的底层设备抽象。
3. Historical Evolution
3. 历史沿革
The shebang mechanism was introduced by Dennis Ritchie at Bell Laboratories between Version 7 and Version 8 of Unix, with kernel support added in January 1980 for Version 8. The feature was also incorporated into BSD releases from Berkeley’s Computer Science Research group, appearing in 2.8BSD and activated by default in 4.2BSD. Since AT&T Bell Laboratories’ Version 8 Unix and subsequent editions were not publicly released, the shebang first became widely known through BSD. The first code implementation is traceable to October 1980 in 4.0BSD, where it was provided as a compile-time option; it was not enabled by default until September 1983 in 4.2BSD.
shebang 机制由 Dennis Ritchie 在贝尔实验室 Unix 第 7 版与第 8 版之间引入,并于 1980 年 1 月为第 8 版 Unix 添加了内核支持。该特性也被纳入伯克利计算机科学研究组发布的 BSD 版本中,在 2.8BSD 中出现,并于 4.2BSD 中默认启用。由于 AT&T 贝尔实验室的第 8 版 Unix 及后续版本未向公众发布,shebang 首次广为人知是通过 BSD。其首次代码实现可追溯至 1980 年 10 月的 4.0BSD,彼时仅作为编译选项提供;直到 1983 年 9 月的 4.2BSD 才被默认启用。
In Version 7 Unix (1979), prior to the kernel-level shebang, the Bourne shell provided a facility whereby files with execute permission were handled specially: the shell would spawn a subshell to interpret the file’s contents, depending on initial characters such as : or #. In this model, scripts behaved as commands only when invoked from within a Bourne shell; direct execution via the operating system’s exec() system call would fail, preventing scripts from behaving uniformly as normal system commands.
在 1979 年的第 7 版 Unix 中,在内核级 shebang 出现之前,Bourne shell 提供了一种机制:对具有执行权限的文件进行特殊处理,shell 会根据首字符(如 : 或 #)生成子 shell 来解释文件内容。在此模型下,脚本仅在 Bourne shell 内部调用时才表现为命令;通过操作系统自身的 exec() 系统调用直接执行则会失败,使脚本无法如普通系统命令般统一表现。
Dennis Ritchie’s 1980 description of the kernel-level implementation stated the following benefits: (1) shell scripts behave more like real executable files because they can be the subject of exec; (2) the ps command displays the script’s real name instead of sh, and system accounting is done on the basis of the real name; (3) shell scripts can be set-user-ID; (4) alternate shells are easier to configure; and (5) other interpreters can integrate more smoothly. The initial implementation restricted the shebang line to 16 characters, a limit that was later raised.
Dennis Ritchie 在 1980 年对内核级实现的描述中列出了以下优势:(1) shell 脚本更接近真正的可执行文件,因为它们可以作为 exec 的对象;(2) ps 命令显示脚本的真实名称而非 sh,系统记账也基于真实名称进行;(3) shell 脚本可以设置为用户标识(set-user-ID)模式;(4) 备用 shell 的配置与使用流程被简化;(5) 其他类型的解释器可以更顺畅地与系统集成。最初的实现将 shebang 行限制为 16 个字符,该限制后来被放宽。
Ritchie later noted that the feature’s creators did not give it a proper name. He recalled obtaining the idea from someone at a UCB (University of California, Berkeley) conference on Berkeley Unix, and that he may have been among the first to install it, though the idea originated elsewhere.
Ritchie 后来指出,该功能的创造者并未为其赋予正式名称。他回忆称,这一想法来自某次加州大学伯克利分校举办的伯克利 Unix 会议上的一位与会者,他可能是最早实际部署该功能的人之一,但该创意并非由他原创。
Modern implementations of the shebang mechanism can be found in the Linux kernel source file fs/binfmt_script.c. Kernel support has spread to most contemporary Unix-like systems, though some systems allow the mechanism to be constrained or disabled for security purposes.
shebang 机制的现代实现可见于 Linux 内核源文件 fs/binfmt_script.c。内核支持已扩展到大多数当代类 Unix 系统,尽管某些系统出于安全目的允许对该机制加以限制或禁用。
4. Kernel-Level Working Principles
4. 内核级工作原理
When a script is executed (e.g., via ./script.sh), the kernel reads the first two bytes of the file. If these bytes correspond to the ASCII characters # and ! (byte values 0x23 and 0x21), the file is recognized as a script rather than a native binary executable. This byte sequence constitutes a human-readable instance of a magic number. The kernel then parses the remainder of the first line to extract the interpreter path and optional argument. The kernel invokes the specified interpreter, passing the script’s pathname as the final argument. Any additional arguments provided on the command line are appended after the script pathname.
当执行脚本时(例如通过 ./script.sh),内核读取文件的前两个字节。若这两个字节的 ASCII 值对应 # 和 !(字节值 0x23 和 0x21),则文件被识别为脚本而非原生二进制可执行文件。该字节序列构成了人类可读的魔数实例。内核随后解析首行剩余部分以提取解释器路径和可选参数。内核调用指定的解释器,并将脚本的路径名作为最后一个参数传入。命令行上提供的任何额外参数均附加在脚本路径名之后。
For example, executing a script with the shebang #!/bin/sh -x via the command some/path/to/foo bar baz results in the kernel invoking:
例如,通过命令 some/path/to/foo bar baz 执行首行为 #!/bin/sh -x 的脚本时,内核将调用:
/bin/sh -x some/path/to/foo bar baz
The processing routine for shebang resides within execve(), which is called internally by exec(). In modern systems such as FreeBSD and Linux, this routine is implemented as a subfunction within execve(). From the implementation perspective, when executing ./something, Linux calls the exec system call with the path ./something. The kernel reads the first few bytes of the file and compares them with #! (see linux/fs/binfmt_script.c: if ((bprm->buf[0] != '#') || (bprm->buf[1] != '!'))). If matched, the kernel parses the remainder of the line and initiates another exec call with the interpreter path and the current file as arguments, effectively equivalent to:
shebang 的处理例程位于 execve() 内部,而 execve() 由 exec() 调用。在现代系统(如 FreeBSD 和 Linux)中,该例程多以 execve() 内部调用的子函数实现。从实现层面看:执行 ./something 时,Linux 以路径 ./something 调用 exec 系统调用。内核读取文件开头的若干字节并与 #! 比较(见 linux/fs/binfmt_script.c 中 if ((bprm->buf[0] != '#') || (bprm->buf[1] != '!')))。若匹配,则解析该行剩余内容,并以解释器路径与当前文件为参数再次发起 exec 调用,效果等价于:
/usr/bin/env python /path/to/script.py
The program loader checks the first 16 bits of the file to determine the executable format; if it is #!, the loader uses the remainder of the first line to determine the program to start, and passes the name of the script being started as the last argument to the interpreter. The interpreter then runs normally and treats the #! line as a comment.
程序装载器检查文件前 16 位以判断可执行格式;若为 #!,则用文件第一行的其余内容确定应启动的程序,并把所尝试启动的脚本文件名作为最后一个参数传给解释器。解释器随后正常运行,并将 #! 行当作注释处理。
When a file begins with different bytes, the exec system call employs different handlers. Another built-in handler is used for ELF executables (see linux/fs/binfmt_elf.c), which checks the first 4 bytes 7f 45 4c 46 (corresponding to the ASCII characters .ELF). The following command can be used to verify the first 4 bytes of /bin/ls:
文件以不同字节开头时,exec 系统调用会使用不同的处理程序。另一项内建处理程序用于 ELF 可执行文件(见 linux/fs/binfmt_elf.c),其检查前 4 个字节 7f 45 4c 46(对应 ASCII 字符 .ELF)。可用以下命令确认 /bin/ls 的前 4 个字节:
head -c 4 "$(which ls)" | hd
Output:
输出:
00000000 7f 45 4c 46 |.ELF|
00000004
Upon seeing these bytes, the kernel loads the ELF file into memory and starts the new process. Additionally, custom shebang handlers can be added via the binfmt_misc mechanism, for example to add a custom handler for .jar files, or to transparently run executables for other architectures using QEMU.
内核看到这些字节后,将 ELF 文件装入内存并启动新进程。此外,可通过 binfmt_misc 机制添加自定义的 shebang 处理程序,例如为 .jar 文件添加自定义处理器,或借助 QEMU 透明运行其他架构的可执行文件。
5. Fallback Behavior Without Shebang
5. 无 Shebang 时的回退机制
If no shebang is present, the kernel typically fails to execute the file directly, returning ENOEXEC (Exec format error). However, some shells (as a legacy behavior from the Bourne shell) may still interpret the file if it has execute permission and is invoked through the shell. In such cases, the user’s default shell interprets the script. More precisely, the shell first attempts to execute the file via execve(); when execve() returns ENOEXEC, the shell falls back to handing the file to /bin/sh or treating it as a shell script. Both Bash and Zsh implement this logic.
若不存在 shebang,内核通常无法直接执行该文件,返回 ENOEXEC(Exec format error)。然而,某些 shell(作为 Bourne shell 的遗留行为)仍可能在文件具有执行权限且通过 shell 调用时解释该文件。此时脚本由用户的默认 shell 解释。更精确的过程是:shell 先尝试通过 execve() 执行文件;当 execve() 返回 ENOEXEC 时,shell 回退,将该文件交给 /bin/sh 或作为 shell 脚本处理。bash 与 zsh 均实现此逻辑。
Furthermore, execlp(), execvp(), and execvpe() provide similar fallback behavior at the library level: when execve(2) returns ENOEXEC, these functions execute the shell (/bin/sh) with the file path as the first argument. POSIX explicitly specifies this behavior. Individual shells typically do not use execlp/execvp directly, but instead implement the same logic with execve for finer control over the execution environment.
此外,execlp()、execvp()、execvpe() 在库层面提供类似回退:当 execve(2) 返回 ENOEXEC 时,这些函数以文件路径作为第一个参数执行 shell(/bin/sh)。POSIX 对此有明确规定。各 shell 通常不直接使用 execlp/execvp,而是用 execve 自行实现相同逻辑,以便对执行环境有更细的控制。
The shebang line is generally ignored by the interpreter itself because the # character introduces comments in many scripting languages. However, this behavior is interpreter-dependent.
shebang 行通常被解释器自身忽略,因为 # 字符在许多脚本语言中用于引入注释。然而,该行为取决于具体解释器。
A script without a shebang line will be executed by the user’s current shell (e.g., sh), which may lack features used in the script. For instance, if a script uses Bash-specific syntax such as [[ "foo" == "foo" ]], execution under sh will fail with an error:
缺少 shebang 行的脚本将由用户当前 shell(如 sh)执行,而该 shell 可能不支持脚本中使用的特性。例如,若脚本使用 bash 专属语法如 [[ "foo" == "foo" ]],在 sh 下执行将报错:
./no_shebang.sh: 2: [[: not found
Scripts intended to be sourced (e.g., via source ./lib.sh) rather than executed directly may still include a shebang line for documentation purposes, though the kernel does not process it during sourcing.
旨在被引用(如通过 source ./lib.sh)而非直接执行的脚本,仍可包含 shebang 行以提供文档说明,尽管内核在引用时不会处理该 shebang。
6. Syntax Specification
6. 语法规范
The shebang line must conform to the following rules:
shebang 行必须符合以下规则:
-
Position: The shebang must appear as the first line of the file. No characters, including whitespace or blank lines, may precede
#!. If the shebang is not the first line, it is ignored.
位置:shebang 必须出现在文件的第一行。#!之前不得有任何字符,包括空格或空行。若 shebang 不在第一行,则会被忽略。 -
Format: The line begins with
#!followed by the absolute path to the interpreter. A single space between#!and the interpreter path is optional. Any spaces or tabs before or after the interpreter path are permitted in some implementations, though for portability the path should immediately follow#!or a single space.
格式:行首为#!,后跟解释器的绝对路径。#!与解释器路径之间的单个空格可选。某些实现允许解释器路径前后存在空格或制表符,但为可移植性起见,路径应紧跟#!或单个空格。 -
Arguments: Only one optional argument may be passed to the interpreter in a portable manner. The argument includes any extra characters up to the end of the line. Embedded whitespace within arguments is not portable across systems.
参数:以可移植方式最多只能向解释器传递一个可选参数。该参数包含从解释器路径后到行尾的所有额外字符。参数中嵌入的空白字符在各系统间不具备可移植性。 -
No comments: Comments or additional text cannot be appended to the shebang line.
无注释:shebang 行不能附加注释或额外文本。
The general form is:
一般形式为:
#! interpreter [optional-argument]
There is a legend that a few specific early Unix versions (particularly 4.2BSD derivatives) required whitespace between #! and the subsequent path, claiming that such kernels parse #! / as a 32-bit (long) magic number. In fact, no genuine Unix requiring whitespace has been identified. 4.2BSD does not require whitespace, although the GNU Autoconf tutorial (Section 5.5, Portable Shell Programming) erroneously claims otherwise. The 4.2BSD source sys/kern_exec.c (around line 123 onwards) accepts but does not require whitespace.
存在一种说法:少数特定的早期 Unix 版本(尤其是 4.2BSD 衍生系统)要求 #! 与后续路径之间以空格分隔,甚至称此类内核会把 #! / 解析为 32 位(长整型)魔数。实际上无法找到真正要求空格的 Unix。4.2BSD 并不要求空格,尽管 GNU autoconf 教程(5.5 节 Portable Shell Programming)错误地如此声称。可参见 4.2BSD 源码 sys/kern_exec.c(约第 123 行起):它接受但不要求空格。
7. Cross-Platform Implementation Differences
7. 跨平台实现差异
Although the basic shebang principle is consistent across Unix-like systems, significant differences exist in implementation details.
尽管 shebang 的基本原理在类 Unix 系统中保持一致,但实现细节存在显著差异。
7.1 Argument Passing
7.1 参数传递
Systems vary in how they parse arguments from the shebang line. On Linux and Cygwin, all text following the first space after the interpreter path is treated as a single argument. For instance, #!/usr/bin/env python3 -c passes the string python3 -c as a single argument to /usr/bin/env, rather than two separate arguments.
各系统对 shebang 行参数的解析方式不同。在 Linux 和 Cygwin 上,解释器路径后第一个空格之后的全部文本被视为单个参数。例如,#!/usr/bin/env python3 -c 将字符串 python3 -c 作为单个参数传给 /usr/bin/env,而非两个独立参数。
FreeBSD 6.0 (2005) introduced the -S option to its env utility to address this limitation, instructing env to split the string into multiple arguments. GNU Coreutils 8.30 (2018) subsequently adopted this feature.
FreeBSD 6.0(2005)为其 env 工具引入了 -S 选项以解决此限制,指示 env 将字符串拆分为多个参数。GNU Coreutils 8.30(2018)随后采用了这一特性。
7.2 Maximum Line Length Limitations
7.2 最大行长度限制
Early implementations imposed strict length limits on the shebang line. The first Version 8 Unix implementation restricted the line to 16 characters. Some later early versions limited it to approximately 32 characters. Modern Linux limits the total length (including #!) to 255 characters (127 characters prior to Linux 5.1). Modern FreeBSD limits the line to approximately 4096 characters. If the shebang line exceeds the system’s maximum, the script may fail to execute, the line may be truncated, or ENOEXEC may be returned, resulting in unexpected behavior.
早期实现对该行长度施加了严格限制。最初的第 8 版 Unix 实现将该行限制为 16 个字符。某些后期早期版本限制在大约 32 个字符。现代 Linux 将总行长度(含 #!)限制为 255 个字符(Linux 5.1 之前为 127 个字符)。现代 FreeBSD 将该行限制为约 4096 个字符。若 shebang 行超过系统最大值,脚本可能无法执行、该行可能被截断,或返回 ENOEXEC,导致意外行为。
7.3 Interpreter Chains
7.3 解释器链
On Linux and Minix, the interpreter specified in a shebang line may itself be another script with a shebang, allowing chains of interpreters. For example, if /bin/A is an ELF binary, /bin/B contains #!/bin/A optparam, and /bin/C contains #!/bin/B, then executing /bin/C resolves to /bin/B /bin/C, which finally resolves to /bin/A optparam /bin/B /bin/C. If nesting is too deep, execve() fails with ELOOP (too many levels of symbolic links).
在 Linux 和 Minix 上,shebang 行中指定的解释器本身可以是另一个带有 shebang 的脚本,从而形成解释器链。例如,若 /bin/A 为 ELF 二进制文件,/bin/B 包含 #!/bin/A optparam,/bin/C 包含 #!/bin/B,则执行 /bin/C 解析为 /bin/B /bin/C,最终解析为 /bin/A optparam /bin/B /bin/C。若嵌套过深,execve() 以 ELOOP(符号链接层级过多)失败。
In Solaris and Darwin-derived systems (including macOS), the interpreter must be an executable binary and cannot itself be a script. FreeBSD also disallows nesting: if the interpreter file itself contains a shebang, execve() returns ENOEXEC, and execution falls back to /bin/sh processing the original script.
在 Solaris 和 Darwin 衍生系统(包括 macOS)中,解释器必须是可执行二进制文件,不能是脚本。FreeBSD 同样不允许嵌套:若解释器文件自身包含 shebang,execve() 返回 ENOEXEC,执行回退为 /bin/sh 处理原脚本。
7.4 Character Encoding and Byte Order Marks
7.4 字符编码与字节序标记
The shebang characters #! are represented by bytes 0x23 and 0x21 in ASCII and UTF-8. However, if a UTF-8 file begins with a Byte Order Mark (BOM, bytes 0xEF 0xBB 0xBF), and the kernel’s exec function specifically checks for 0x23 and 0x21 at the very beginning, the BOM prevents the shebang from being recognized. The use of BOM in POSIX scripts is therefore not recommended. Additionally, a BOM is unnecessary in UTF-8, as that encoding does not have endianness issues.
shebang 字符 #! 在 ASCII 和 UTF-8 中由字节 0x23 和 0x21 表示。然而,若 UTF-8 文件以字节序标记(BOM,字节 0xEF 0xBB 0xBF)开头,且内核的 exec 函数专门检查开头的 0x23 和 0x21,则 BOM 会阻止 shebang 被识别。因此,不建议在 POSIX 脚本中使用 BOM。此外,UTF-8 无需字节序标记,因为该编码不存在字节序问题。
7.5 Line Endings
7.5 行结束符
Scripts edited on systems using DOS/Windows line endings (CRLF, \r\n) may fail to execute because the carriage return character (\r) is interpreted as part of the interpreter path. The kernel attempts to execute #!/bin/bash\r, which does not exist. Scripts should use Unix line endings (LF, \n).
在使用 DOS/Windows 行结束符(CRLF,\r\n)的系统上编辑的脚本可能无法执行,因为回车符(\r)被解释为解释器路径的一部分。内核尝试执行 #!/bin/bash\r,而该路径不存在。脚本应使用 Unix 行结束符(LF,\n)。
8. Portability and the env Utility
8. 可移植性与 env 工具
8.1 Absolute Path Issues
8.1 绝对路径问题
Shebang lines must specify absolute paths to interpreters. This causes portability problems on systems with non-standard filesystem layouts. Even on systems with standard paths, different variants of the same operating system may place interpreters in different locations. For example, Python 3 might reside in /usr/bin/python3, /usr/local/bin/python3, or a user-specific directory. On FreeBSD, additionally installed programs reside under /usr/local; thus Bash is located at /usr/local/bin/bash rather than /bin/bash. A script with #!/bin/bash will fail with Command not found on FreeBSD even though the script itself exists.
shebang 行必须指定解释器的绝对路径。这在文件系统布局非标准的系统上可能导致可移植性问题。即使在路径标准的系统上,同一操作系统的不同变体也可能将解释器置于不同位置。例如,Python 3 可能位于 /usr/bin/python3、/usr/local/bin/python3 或用户特定目录中。在 FreeBSD 上,额外安装的程序位于 /usr/local 之下,因此 bash 位于 /usr/local/bin/bash 而非 /bin/bash。包含 #!/bin/bash 的脚本在 FreeBSD 上会因解释器不存在而报 Command not found,即便脚本文件本身存在。
POSIX requires the shell to be named sh but does not mandate a path. While /bin/sh is common, Solaris places the POSIX-compatible shell at /usr/xpg4/bin/sh. Using bash-specific syntax with a shebang pointing to sh is not portable.
POSIX 要求 shell 名为 sh,但未规定路径。虽然 /bin/sh 较为常见,但 Solaris 将 POSIX 兼容 shell 置于 /usr/xpg4/bin/sh。在 shebang 指向 sh 的同时使用 bash 专属语法不具备可移植性。
Because POSIX does not standardize path names, POSIX does not standardize the shebang feature itself. The GNU Autoconf tool can test for system support with the macro AC_SYS_INTERPRETER.
由于 POSIX 未标准化路径名,POSIX 也未标准化 shebang 特性本身。GNU Autoconf 工具可通过宏 AC_SYS_INTERPRETER 测试系统支持。
8.2 The env Utility and PATH Resolution
8.2 env 工具与 PATH 搜索
The /usr/bin/env utility provides a level of indirection that improves portability. A shebang of the form #!/usr/bin/env interpreter causes env to search the user’s PATH environment variable for the interpreter, avoiding hardcoded absolute paths.
/usr/bin/env 工具提供了一层间接性以提升可移植性。形式为 #!/usr/bin/env interpreter 的 shebang 使 env 在用户的 PATH 环境变量中搜索解释器,避免了硬编码的绝对路径。
This approach is not universal. Some systems, such as OpenServer 5.0.6 and Unicos 9.0.2, provide env only at /bin/env rather than /usr/bin/env. Furthermore, using /usr/bin/env introduces runtime indirection that may have security implications, as it relies on the PATH variable being correctly configured.
此方法并非普适。某些系统(如 OpenServer 5.0.6 和 Unicos 9.0.2)仅在 /bin/env 提供 env,而非 /usr/bin/env。此外,使用 /usr/bin/env 引入了运行期间接性,可能带来安全影响,因为它依赖于 PATH 变量被正确配置。
8.3 Multiple Argument Passing and env -S
8.3 多参数传递与 env -S
Most systems treat all text after the interpreter path in the shebang line as a single argument. To pass multiple arguments to the interpreter via env, the -S option (available in FreeBSD 6.0+ and GNU Coreutils 8.30+) can be used:
大多数系统将 shebang 行中解释器路径后的所有文本视为单个参数。要通过 env 向解释器传递多个参数,可使用 -S 选项(FreeBSD 6.0+ 和 GNU Coreutils 8.30+ 可用):
#!/usr/bin/env -S perl -T -w
This splits the string into multiple arguments before invoking the interpreter.
这在调用解释器前将字符串拆分为多个参数。
Interpreter arguments may also be appended directly to the shebang line to modify behavior. Common options for Bash include:
解释器参数也可直接附加在 shebang 行后以修改行为。Bash 常用选项包括:
-e: Exit immediately if any command fails.
-e:任何命令执行失败时立即退出-u: Treat unset variables as errors.
-u:将未定义的变量视为错误-x: Print each command before execution.
-x:执行前打印每个命令-o pipefail: Make pipelines fail if any command in the pipeline fails.
-o pipefail:管道中任一命令失败时,整个管道视为失败
Example:
示例:
#!/usr/bin/env bash -euo pipefail
Note that passing complex arguments directly in the shebang line may break portability on some systems. A more robust approach is to place set -euo pipefail inside the script body.
注意直接在 shebang 行传递复杂参数可能在某些系统上破坏可移植性。更健壮的做法是在脚本内部放置 set -euo pipefail。
9. Security Considerations
9. 安全考量
9.1 setuid Scripts
9.1 setuid 脚本
The interaction between shebang mechanisms and setuid (set-user-ID) execution is complex. Early Unix versions allowed shell scripts to be setuid, but most modern operating systems have disabled this feature due to race condition vulnerabilities: a malicious user might replace or modify the script between the kernel’s permission check and the interpreter’s opening of the file.
shebang 机制与 setuid(set-user-ID)执行之间的交互较为复杂。早期 Unix 版本允许 shell 脚本设置为 setuid,但大多数现代操作系统已禁用此功能,原因是存在竞态条件漏洞:恶意用户可能在内核进行权限检查与解释器打开文件之间的间隙替换或篡改脚本。
When a setuid script is executed, the kernel reads the shebang line and invokes the interpreter. The interpreter then opens the script file as a regular user. If an attacker changes the file contents between these two operations, the interpreter may execute malicious code with elevated privileges. To mitigate this risk, many systems ignore the setuid bit on scripts entirely, or restrict the use of setuid scripts to specific controlled environments. Modern FreeBSD and Linux ignore the setuid bit on scripts; the effective user ID does not change.
当执行 setuid 脚本时,内核读取 shebang 行并调用解释器,随后解释器以普通用户身份打开脚本文件。若攻击者在这两个操作之间更改文件内容,解释器可能以提升的权限执行恶意代码。为降低此风险,许多系统完全忽略脚本上的 setuid 位,或将 setuid 脚本的使用限制在特定受控环境中。现代 FreeBSD 与 Linux 均忽略脚本的 setuid 位,有效用户 ID 不会提升。
9.2 Interpreter Path Validation
9.2 解释器路径验证
The kernel executes the interpreter specified in the shebang line without further validation of the interpreter’s trustworthiness. If the interpreter path is compromised (e.g., pointing to a malicious binary), the script will execute under the attacker’s control. Hardcoding absolute paths reduces this risk compared to using /usr/bin/env, which relies on the PATH environment variable and is therefore susceptible to PATH manipulation attacks.
内核执行 shebang 行中指定的解释器,而不进一步验证解释器的可信度。若解释器路径被篡改(例如指向恶意二进制文件),脚本将在攻击者的控制下执行。与使用依赖 PATH 环境变量、易受 PATH 操纵攻击的 /usr/bin/env 相比,硬编码绝对路径可降低此风险。
9.3 Restricted Shell
9.3 受限 Shell
For scenarios requiring controlled execution environments, Bash provides the restricted mode invoked via #!/bin/bash -r. In restricted mode, operations such as changing directories (cd), modifying PATH, redirecting output, and executing commands with absolute paths are prohibited. This mode is useful for creating sandboxed execution contexts but does not replace proper filesystem permissions and access controls.
对于需要受控执行环境的场景,Bash 提供了通过 #!/bin/bash -r 调用的受限模式。在受限模式下,切换目录(cd)、修改 PATH、重定向输出以及使用绝对路径执行命令等操作均被禁止。该模式适用于创建沙盒执行上下文,但不能替代适当的文件系统权限和访问控制。
10. Common Shebang Directives and Examples
10. 常见 Shebang 指令与示例
The following table summarizes frequently used shebang lines for various interpreters:
下表汇总了各类解释器常用的 shebang 行:
| Shebang | Interpreter | Description |
|---|---|---|
#!/bin/sh | Bourne Shell | POSIX-compliant shell interpreter. On many systems, /bin/sh is a symlink to bash, dash, or ksh. 符合 POSIX 标准的 shell 解释器。在许多系统上, /bin/sh 是指向 bash、dash 或 ksh 的符号链接。 |
#!/bin/bash | Bash | GNU Bourne-Again Shell at fixed path /bin/bash. 固定路径 /bin/bash 下的 GNU Bourne-Again Shell。 |
#!/usr/bin/env bash | Bash (via env) | Locates bash via PATH; highly portable. 通过 PATH 定位 bash;可移植性极强。 |
#!/usr/bin/env python3 | Python 3 | Locates Python 3 interpreter via PATH. 通过 PATH 定位 Python 3 解释器。 |
#!/usr/bin/perl | Perl | Direct path to Perl interpreter. Perl 解释器的直接路径。 |
#!/usr/bin/env ruby | Ruby | Locates Ruby interpreter via PATH. 通过 PATH 定位 Ruby 解释器。 |
#!/usr/bin/pwsh | PowerShell | Direct path to PowerShell interpreter. PowerShell 解释器的直接路径。 |
#!/bin/false | No-op | Returns non-zero exit status; prevents standalone execution. 返回非零退出状态;用于阻止独立执行。 |
10.1 Basic Bash Script
10.1 基础 Bash 脚本
Create a file named hello_bash.sh with the following contents:
创建名为 hello_bash.sh 的文件,内容如下:
#!/bin/bash
echo "Hello from bash!"
echo "Current shell: $0"
Make the script executable and run it:
赋予执行权限并运行:
chmod +x hello_bash.sh
./hello_bash.sh
Output:
输出:
Hello from bash!
Current shell: /bin/bash
10.2 Using env for Portability
10.2 使用 env 提升可移植性
On systems where bash is not located at /bin/bash (e.g., macOS, BSD), use #!/usr/bin/env bash:
在 bash 不位于 /bin/bash 的系统上(如 macOS、BSD),使用 #!/usr/bin/env bash:
#!/usr/bin/env bash
echo "Hello from portable bash!"
echo "Bash path: $(which bash)"
Output on macOS:
macOS 上的输出:
Hello from portable bash!
Bash path: /usr/local/bin/bash
11. Troubleshooting
11. 问题排查
| Symptom 现象 | Cause 原因 | Resolution 解决方法 |
|---|---|---|
Permission denied 权限拒绝 | Script lacks execute permission. 脚本缺少执行权限。 | Run chmod +x script.sh. 执行 chmod +x script.sh。 |
No such file or directory 没有该文件或目录 | Interpreter path is invalid. 解释器路径无效。 | Verify with which interpreter; use #!/usr/bin/env interpreter. 使用 which interpreter 验证;改用 #!/usr/bin/env interpreter。 |
| Script runs in wrong shell 脚本在错误的 shell 中运行 | Shebang missing or preceded by whitespace. 缺少 shebang 或 shebang 前有空白。 | Ensure #! is the first two bytes of the file. 确保 #! 为文件的前两个字节。 |
Bad interpreter: Text file busy 错误解释器:文本文件忙 | Script is open in an editor or being written. 脚本正在编辑器中打开或被写入。 | Close the file and retry. 关闭文件后重试。 |
#!/bin/bash^M: bad interpreter #!/bin/bash^M:错误的解释器 | CRLF line endings from Windows editing. 来自 Windows 编辑的 CRLF 行结束符。 | Convert with dos2unix script.sh or set editor to LF mode. 使用 dos2unix script.sh 转换或将编辑器设为 LF 模式。 |
/usr/bin/env: 'bash': No such file or directory /usr/bin/env: 'bash':没有该文件或目录 | Interpreter not in PATH. 解释器不在 PATH 中。 | Install interpreter or add its path to PATH. 安装解释器或将其路径加入 PATH。 |
12. Shell Script Robustness and Portability
12. Shell 脚本的健壮性与可移植性
Shell is the primary domain-specific language designed to manipulate the Unix abstractions for data and logic, i.e., files and processes. Scripts that deviate from these abstractions and perform significant data manipulation within the shell process itself become unwieldy. Effective shell programming requires thorough knowledge of available Unix tools.
Shell 是一门主要的领域专用语言,被设计用来操作 UNIX 的数据与逻辑抽象概念,也就是文件与进程。脱离这类抽象、在 shell 进程内部执行大量数据处理的脚本会变得难以维护。熟练掌握各类 UNIX 工具,是写出高效 shell 脚本的必要条件。
12.1 Stylistic Issues
12.1 代码风格问题
The idiom x"$var" was required in cases where historical shells failed to distinguish strings beginning with a hyphen, such as -hyphen. These are old bugs; newer scripts should avoid propagating this idiom.
x"$var" 这种写法的出现,是为了解决早期 shell 无法识别以短横线开头(如 -hyphen)字符串的历史缺陷。这些属于老旧 bug,新脚本应当避免沿用这种写法。
Testing [ ! -z "$var" ] is a double negative. Test the string directly: [ "$var" ] && echo "var not empty".
[ ! -z "$var" ] 是双重否定写法。可以直接对字符串做判断:[ "$var" ] && echo "var not empty"。
Setting a variable only if it is not previously set can be expressed as : "${var=value}". To set a variable if it is empty or unset, use : "${var:=value}". Do not use : ${var="value"}, as that exposes var to globbing (ShellCheck rule SC2223).
仅当变量未定义时才对其赋值,可以使用 : "${var=value}" 实现更简短的表达。如果变量为空字符串或者未定义都要赋值,则使用 : "${var:=value}"。以上写法可以在绝大多数 shell 环境中移植。不要使用 : ${var="value"},该写法会让变量受到通配符扩展的影响,对应 shellcheck 规则为 SC2223。
The redundant use of $? should be avoided. Instead of:
应避免多余使用 $?。不要这样写:
pidof program
if [ $? = 1 ]; then
echo "program not found"
fi
Test the exit status directly:
直接判断退出状态:
if ! pidof program; then
echo "program not found"
fi
Be careful when checking negative returns, as any failure (including I/O errors) produces a non-zero exit status. If using grep to verify that there is no match, capturing $? is not redundant:
在判断否定返回结果时需要留意:各类故障(例如 I/O 错误)都会返回非 0 退出码。例如需要用 grep 判断不存在匹配内容时,使用 $? 就不属于多余写法:
grep -q 'regex' FILE; local st=$?
if [ $st = 1 ]; then
echo no-match
fi
12.2 Globbing and Word Splitting
12.2 通配符扩展与单词切分
The following pattern is neither scalable nor robust:
以下写法扩展性与健壮性都很差:
for file in `ls *`; do
wc -l $file
done
This idiom redundantly starts an ls process, fails to handle filenames containing spaces due to word splitting, and may overflow static command line buffers on some systems. Use the shell’s built-in globbing instead:
该写法额外启动 ls 进程列出文件,执行过程会进行单词切分,无法处理文件名带空格的场景;在部分系统中,文件数量巨大时还会造成命令行静态缓冲区溢出。直接使用 shell 原生的通配符扩展:
for file in *; do
wc -l -- "$file"
done
The -- option indicates to wc to stop option processing, immunizing against filenames starting with -. Note that this still spawns a wc process per file; for scalability, functional techniques should be preferred.
-- 参数用来告诉 wc 停止解析命令行选项,以此兼容以短横线 - 开头的文件名。注意该写法依旧会为每一个文件新建 wc 进程;追求可伸缩性时,应尽量使用函数式思路。
12.3 Quoting and Pathnames
12.3 引号引用与路径名
Shell quoting guidelines for handling pathnames correctly are as follows:
正确处理路径名的 shell 引号引用规则如下:
-
Double-quote all variable references and command substitutions unless you are certain they can only contain alphanumeric characters. In particular,
$@should practically always be inside double-quotes; POSIX defines this to expand into positional parameters as separate fields even within double-quotes.
对所有变量引用、命令替换都使用双引号包裹,除非可以确定内容仅由字母数字构成。尤其$@几乎始终需要放在双引号内部;POSIX 对其做特殊定义,即使在双引号内,依旧会把各个位置参数展开为独立字段。 -
Set
IFSto just newline and tab to reduce the risk of mishandling filenames with spaces:IFS="$(printf '\n\t')".
在条件允许时,将IFS仅设置为换行符与制表符,降低带空格文件名被错误解析的风险。使用IFS="$(printf '\n\t')"完成IFS设置。 -
Prefix all pathname globs so they cannot expand to begin with
-. Never start a glob with?or*(such as*.pdf); always prepend something like./. Use./*.pdfinstead of*.pdf.
给所有路径通配符增加前缀,避免展开结果以-开头。不要用?、*作为通配符的起始字符(例如*.pdf);通配符前面始终拼接不会被解析为短横线的内容,例如./。不要写*.pdf,改用./*.pdf。 -
When accepting pathnames, check if a pathname begins with
-and prepend./if it does.
接收路径参数时,检查路径是否以-开头,如果是,在前面拼接./。 -
Be careful about displaying or storing pathnames, since they can include newlines, tabs, terminal control escape sequences, and non-UTF-8 characters. Control characters can be stripped before display using
printf '%s' "$file" | LC_ALL=POSIX tr -d '[:cntrl:]' | iconv -cs -f UTF-8 -t UTF-8.
展示或存储路径时要格外小心,文件名可以包含换行符、制表符、终端控制转义序列、非 UTF-8 字符等。输出前可以清理控制字符与非 UTF-8 字符:printf '%s' "$file" | LC_ALL=POSIX tr -d '[:cntrl:]' | iconv -cs -f UTF-8 -t UTF-8。 -
Do not depend on
--between options and pathnames as the primary countermeasure. Many programs (includingecho) do not support--.
不要把在选项与路径间使用--作为抵御-开头文件名的主要手段。很多程序(包含echo)并不支持--。 -
Use a tool like ShellCheck to find missed problems.
使用 ShellCheck 这类工具,找出人工遗漏的问题。
12.4 Stopping Automatically on Error
12.4 出错时自动终止脚本
Execute set -e at the top of the script to terminate immediately when any command fails (unless the command is part of a conditional). For Bash, consider the unofficial strict mode: set -euo pipefail.
在脚本开头执行 set -e,一般可以达到预期效果:非条件判断内的命令一旦失败,脚本就终止运行。对于 Bash,可考虑非官方严格模式:set -euo pipefail。
12.5 Cleaning Up Temporary Files
12.5 清理临时文件
Temporary files should be avoided where possible; use pipes to pass data between processes. If temporary files are necessary, use trap to ensure cleanup on exit:
出于性能与可维护性,应当尽量避免临时文件;进程间传递数据优先使用管道。如果确实需要临时文件,可以使用 trap 信号捕获机制确保退出时清理:
#!/bin/sh
tf=/tmp/tf.$$
cleanup() {
rm -f $tf
}
trap "cleanup" EXIT
touch $tf
echo "$tf created"
sleep 10
12.6 Echoing Errors
12.6 错误信息输出
Output errors to standard error: echo "Error occurred" >&2. This allows normal output to be piped or redirected independently.
把错误输出到标准错误流 stderr:echo "Error occurred" >&2。这样标准输出可以单独重定向或管道转发。
12.7 Bashisms and Portability
12.7 Bash 专属语法与可移植性
bash is the most common interactive shell, and consequently bash-specific syntax is often used in scripts. However, syntax such as [ "$var" == "find" ] uses a double equals that is redundant in shell conditionals and gives a syntax error on older busybox (ash) and dash. Brace expansion (echo {not,portable}) is not portable. Signal specifications for trap vary: CHLD is portable, whereas sigchld, SIGCHLD, chld, or 17 are not.
bash 是 UNIX 环境最常用的交互式 shell,因此很多脚本会使用 bash 独有的语法。然而,[ "$var" == "find" ] 中的双等号在 shell 条件语句中属于多余写法,在旧版 busybox(ash)、dash 环境中还会报语法错误。花括号扩展语法(echo {not,portable})不具备可移植性。trap 命令的信号名称写法各异:CHLD 具备可移植性,而 sigchld、SIGCHLD、chld、17 不具备。
Command substitution using $(...) and arithmetic expansion $((...)) are portable. Avoid the non-portable $[1+1] arithmetic form. Use printf instead of echo when passing variable parameters, as echo implementations vary in their handling of escape sequences and options.
使用 $(...) 进行命令替换以及 $((...)) 进行算术扩展具备可移植性。避免使用不可移植的 $[1+1] 算术写法。传入可变参数时优先使用 printf 而非 echo,因为不同系统 echo 对转义字符、命令选项的处理行为不一致。
12.8 Performance Considerations
12.8 性能考量
Spawning a process per file in a loop is slow. Comparing bash and dash for 30,000 files shows that dash forks wc processes nearly twice as fast as bash, and its base looping is nearly six times faster. The most efficient solution uses compiled utilities:
在循环中为每个文件新建进程开销很大。对 30,000 个文件对比 bash 与 dash:dash 创建 wc 子进程的速度几乎是 bash 的两倍,且纯循环速度接近 bash 的 6 倍。最高效的方案是使用已编译的工具:
find -type f -print0 | wc -l --files0-from=- | tail -n1
This illustrates that shell scripts should do as little as possible in the interpreter itself, and instead connect existing logic in compiled utilities.
这印证一个观点:shell 脚本内部业务逻辑尽量精简,shell 只用来串联 UNIX 系统自带工具已有的处理逻辑。
Disk seeks are expensive. The expression [ -e FOO -o -e BAR ] does not short-circuit and performs two disk seeks. The bash-specific [ -e FOO || -e BAR ] short-circuits, but the portable and efficient form is [ -e FOO ] || [ -e BAR ].
磁盘寻道开销很高。[ -e FOO -o -e BAR ] 不会做短路求值,会触发两次磁盘查询。bash 专属写法 [ -e FOO || -e BAR ] 可以短路第二个判断,但更推荐 [ -e FOO ] || [ -e BAR ],同时兼顾可移植性与运行效率。
13. POSIX Pathnames and File Processing
13. POSIX 路径名与文件处理
Shell programming is remarkably easy in many cases; what is problematic is that the common case of file processing is far more complicated than necessary. This is not a problem limited to shell; correctly processing POSIX pathnames is difficult in all languages. Fundamentally, the rules on pathnames are too permissive.
在很多情况下,shell 编程非常简单;令人遗憾的是,文件处理这一常见场景远比所需复杂。这并非 shell 独有的问题;在所有语言中正确处理 POSIX 路径名都很困难。从根本上说,路径名规则过于宽松。
13.1 Globbing Problems
13.1 通配符问题
Two basic problems exist with globbing:
通配符存在两个基本问题:
-
Globbing returns the pattern itself when there are zero matches. A
nullgloboption should exist so that an empty list is returned if nothing matches and at least one metacharacter was present.
shell 中的通配符在无匹配时返回模式本身。应存在一个nullglob选项,使得在无任何匹配且至少包含一个元字符时返回空列表。 -
Globbing returns pathnames beginning with
-. An option should exist that prepends./to any glob result beginning with-.
通配符通常返回以-开头的路径名。应存在一个选项,启用后为任何以-开头的通配结果添加./前缀。
13.2 Find and Null Separators
13.2 find 与空字符分隔符
POSIX 2023 added several useful features (bugid:243):
POSIX 于 2023 年增加了若干实用特性(bugid:243):
-
find -print0prints pathnames with null byte terminators.
find -print0以 null 字节终止符输出路径名。 -
xargs -0reads pathnames with null byte terminators and performs no other processing:
xargs -0以 null 字节终止符读取路径名(且不对路径名做其他处理):find . -print0 | xargs -0 COMMAND -
The shell
readcommand has been extended so that-d ""reads to a null byte. An unprocessed line can be read usingIFS="" read -d "" -r.
shell 的read命令已扩展,-d ""可读取到 null 字节为止。可使用IFS="" read -d "" -r读取未处理的行。 -
The shell
$'...'construct has been added to the POSIX standard, making it easier to generate newlines and other special characters (bugid:249).
shell 的$'...'构造也已纳入 POSIX 标准,便于生成换行符等特殊字符(bugid:249)。
A proposed -0 option for read would simplify processing further: find . -print0 | while read -0 file; do ... done.
建议为 read 新增 -0 选项,可进一步简化处理:find . -print0 | while read -0 file; do ... done。
13.3 Limiting Pathnames
13.3 限制路径名
It would be much simpler if systems imposed rules on pathnames, such as prohibiting control characters (bugid:251), prohibiting leading -, and requiring pathnames to be UTF-8. Then pathnames could always be printed safely, and standard shell constructs would always work. Since not all systems will limit pathnames, standard mechanisms for handling unrestricted pathnames are still needed. However, restricting pathnames makes systems far easier to use correctly.
若系统对路径名施加规则,如禁止控制字符(bugid:251)、禁止前导 -、要求路径名为 UTF-8,则会简单得多。此后可安全地打印所有路径名,标准 shell 构造将始终有效。由于并非所有系统都会限制路径名,因此仍需要处理无限制路径名的标准机制。然而,限制路径名使系统更易于正确使用。
14. Best Practices
14. 最佳实践
-
Always include a shebang line: Every executable script should begin with a shebang to ensure deterministic interpreter selection. The shebang must be the first two bytes of the file.
始终包含 shebang 行:每个可执行脚本应以 shebang 开头,以确保解释器选择的确定性。shebang 必须位于文件前两个字节。 -
Use
#!/usr/bin/env interpreterfor portability: When cross-platform compatibility is required, employenvto locate the interpreter viaPATH.
为可移植性使用#!/usr/bin/env interpreter:当需要跨平台兼容性时,使用env通过PATH定位解释器。 -
Keep the shebang line clean and concise: Do not append comments or extraneous text. Place comments on subsequent lines.
保持 shebang 行简洁:不要在 shebang 行附加注释或多余文本。将注释置于后续行。 -
Respect line length limitations: Avoid overly long interpreter paths or multiple arguments in the shebang line. Use
env -Sif multiple arguments are necessary.
遵守行长度限制:避免在 shebang 行中使用过长的解释器路径或多个参数。若需多个参数,使用env -S。 -
Use Unix line endings (LF): Ensure scripts use
\nrather than\r\n.
使用 Unix 行结束符(LF):确保脚本使用\n而非\r\n。 -
Avoid setuid scripts: Do not rely on setuid semantics for scripts. Implement privilege escalation through other secure mechanisms.
避免 setuid 脚本:不要依赖脚本的 setuid 语义。通过其他安全机制实现权限提升。 -
Validate interpreter existence: Before deployment, verify that the specified interpreter exists on target systems.
验证解释器存在性:部署前,验证目标系统上存在指定的解释器。 -
Use strict mode for Bash scripts: Consider
#!/usr/bin/env bashwithset -euo pipefailinside the script.
对 Bash 脚本使用严格模式:考虑在脚本内部使用set -euo pipefail,而非直接在 shebang 行附加参数。 -
Quote all variable references: Use double quotes around
"$variable","$@", and command substitutions.
对所有变量引用加引号:对"$variable"、"$@"和命令替换使用双引号。 -
Use
printfinstead ofecho: For variable output,printfhas a more standard implementation across systems.
使用printf替代echo:对于可变输出,printf在各系统上行为更加标准统一。 -
Avoid unnecessary shell logic: Use
mkdir -pandrm -finstead of testing for existence first. Leverage compiled utilities over shell loops.
避免不必要的 shell 逻辑:直接使用mkdir -p和rm -f,无需先判断存在性。优先使用已编译工具替代 shell 循环。
15. Conclusion
15. 结论
The Unix shebang mechanism is a fundamental component of script execution in Unix-like operating systems. Introduced by Dennis Ritchie in 1980, it bridges the gap between interpreted scripts and native executable binaries by allowing the kernel to delegate script execution to the appropriate interpreter. The kernel detects the #! magic number in execve(), parses the interpreter path, and re-executes the specified interpreter with the script as an argument.
Unix shebang 机制是类 Unix 操作系统中脚本执行的基础组件。该机制由 Dennis Ritchie 于 1980 年引入,通过允许内核将脚本执行委托给相应的解释器,弥合了解释型脚本与原生可执行二进制文件之间的差距。内核在 execve() 中检测 #! 魔数,解析解释器路径,并以脚本为参数重新执行指定的解释器。
Despite its apparent simplicity, the shebang exhibits nuanced behavior across different platforms regarding argument passing, line length limits, interpreter chaining, and security interactions. A thorough understanding of these details, combined with rigorous attention to quoting, pathname handling, and portability constraints, is essential for writing robust, portable, and secure scripts.
尽管表面上简单,shebang 在不同平台上关于参数传递、行长度限制、解释器链和安全交互方面表现出复杂的行为。深入理解这些细节,并严格注意引号规则、路径名处理与可移植性约束,对于编写健壮、可移植且安全的脚本至关重要。
By adhering to established best practices—such as using #!/usr/bin/env for portability, maintaining clean shebang lines, respecting system limitations, avoiding setuid scripts, and minimizing logic within the shell interpreter—developers can ensure consistent and predictable behavior across diverse Unix environments.
通过遵循既定最佳实践——例如为可移植性使用 #!/usr/bin/env、保持 shebang 行整洁、遵守系统限制、避免 setuid 脚本、最小化 shell 解释器内部逻辑——开发人员可以确保脚本在不同 Unix 环境中表现一致且可预测。
References
参考文献
一、专著
[1] Cooper M. Advanced Bash Scripting Guide 5.3 Volume 1[M]. lulu.com, 2010.
[2] MacDonald M. HTML5: The Missing Manual[M]. Sebastopol, CA: O’Reilly Media, 2011.
[3] Lutz M. Learning Python (4th ed.)[M]. O’Reilly Media, 2009.
[4] Guelich S, Gundavaram S, Birznieks S. CGI Programming with PERL (2nd ed.)[M]. O’Reilly Media, 2000.
[5] Lie Hetland M. Beginning Python: From Novice to Professional[M]. Apress, 2005.
[6] Schitka J. Linux+ Guide to Linux Certification[M]. Course Technology, 2002.
二、标准与规范
[7] The Open Group. The Open Group Base Specifications Issue 7: Shell Command Language[S]. 2008.
[8] IEEE. IEEE Std 1003.1-2017: Shell Command Language[S]. 2018.
[9] POSIX.1-2017. Shell Command Language[S]. IEEE Std 1003.1-2017.
三、手册页与官方文档
[10] execve(2)[EB/OL]. Linux man page, 2010. https://linux.die.net/man/2/execve
[11] execve(2)[EB/OL]. Linux man pages. https://man7.org/linux/man-pages/man2/execve.2.html
[12] Bash Reference Manual: Invoking Bash[EB/OL]. GNU. https://www.gnu.org/software/bash/manual/html_node/Invoking-Bash.html
[13] env(1)[EB/OL]. FreeBSD General Commands Manual.
[14] GNU Coreutils: env Invocation[EB/OL]. https://www.gnu.org/software/coreutils/manual/html_node/env-invocation.html
[15] SRFI 22[EB/OL]. https://srfi.schemers.org/srfi-22/
四、历史文献
[16] Ritchie D M. Early mail regarding the shebang mechanism[Z]. Archived in 4BSD /usr/src/sys/newsys/sys1.c, 1980.
[17] Richie D. Dennis Ritchie and Hash‑Bang[EB/OL]. Talisman.org. https://www.talisman.org/~erlkonig/documents/dennis‑ritchie‑and‑hash‑bang.shtml
[18] Bell Labs. UNIX TIME‑SHARING SYSTEM: UNIX PROGRAMMER’S MANUAL (PDF)[M]. Vol. 2A (7th ed.), 1979.
[19] CSRG Archive CD‑ROMs[DB/OL]. http://www.mckusick.com/csrg
[20] Toomey W. The Unix Tree[DB/OL]. The Unix Heritage Society. https://minnie.tuhs.org/cgi‑bin/utree.pl
五、期刊论文
[21] Rubini A. Playing with Binary Formats[J]. Linux Journal, 1997(12).
六、在线技术文章
[22] Maschek S. The #! magic, details about the shebang/hash‑bang mechanism[EB/OL]. 2010. https://www.in‑ulm.de/~mascheck/various/shebang/
[23] Maschek S. The #! magic, details about the shebang/hash‑bang mechanism on various Unix flavours[EB/OL]. 2021. https://www.in‑ulm.de/~mascheck/various/shebang/
[24] PixelBeat. Common shell script mistakes[EB/OL]. http://www.pixelbeat.org/programming/shell_script_mistakes.html
[25] Wheeler D A. Filenames and Pathnames in Shell: How to do it Correctly[EB/OL]. https://dwheeler.com/essays/filenames‑in‑shell.html
[26] Wheeler D A. Fixing Unix/Linux/POSIX Filenames[EB/OL]. https://dwheeler.com/essays/fixing‑unix‑linux‑posix‑filenames.html
[27] Maxwell A. Unofficial Bash Strict Mode[EB/OL]. http://redsymbol.net/articles/unofficial‑bash‑strict‑mode/
[28] Google. Google Shell Style Guide[EB/OL]. https://google.github.io/styleguide/shell.xml
[29] Wall L. Perl didn’t grok setuid scripts that had a space on the first line between the shebang and the interpreter name[EB/OL]. USENET. https://groups.google.com/group/comp.sources.bugs/
七、社区问答
[30] Python3 shebang line not working as expected[EB/OL]. Stack Overflow, 2017. https://stackoverflow.com/questions/45444823/
[31] How does the #! shebang work?[EB/OL]. Stack Overflow. https://stackoverflow.com/questions/3009192/
[32] What exactly happens when I execute a file in my shell?[EB/OL]. Unix & Linux Stack Exchange. https://unix.stackexchange.com/questions/268766/
[33] Shebang and path[EB/OL]. Unix & Linux Stack Exchange. https://unix.stackexchange.com/questions/11907/
[34] Gilles. Why is SUID disabled for shell scripts but not for binaries?[EB/OL]. Information Security Stack Exchange. https://security.stackexchange.com/a/194174
[35] Carriage Return causes bash to fail[EB/OL]. Ask Ubuntu, 2013. https://askubuntu.com/questions/372672/
八、其他在线资源
[36] What’s with #!/usr/bin/env bash?[EB/OL]. https://burnthewhich.github.io/shbangenv/shbangenv
[37] /usr/bin/env behaviour[EB/OL]. Mail‑index.netbsd.org, 2008.
[38] Unicode. FAQ UTF‑8, UTF‑16, UTF‑32 & BOM[EB/OL]. https://www.unicode.org/faq/utf_bom.html
[39] Jargon File entry for shebang[EB/OL]. http://catb.org/jargon/html/S/shebang.html
[40] GNU Autoconf. AC_SYS_INTERPRETER[EB/OL]. https://www.gnu.org/software/autoconf/manual/autoconf‑2.67/autoconf.html
[41] GNU Autoconf Manual v2.57, Chapter 10: Portable Shell Programming[EB/OL]. https://www.gnu.org/software/autoconf/manual/autoconf‑2.57/html_chapter/autoconf_10.html
[42] A History of the Shebang[EB/OL]. https://zenn.dev/kusaremkn/articles/5b2a87852005cd
[43] Details about the shebang mechanism[EB/OL]. https://homepages.cwi.nl/~aeb/std/shebang/
[44] DevGex. Comprehensive Analysis of Shebang in Unix/Linux Scripts[EB/OL]. https://devgex.com/en/article/00003106
[45] Jcroyoaun. A deeper view into the Shebang for Linux Scripting[EB/OL]. Medium. https://medium.com/@jcroyoaun/a‑deeper‑view‑into‑the‑shebang‑for‑linux‑scripting‑4a26395df49d
[46] Demystifying the Shebang: A Deep Dive into #!/bin/bash[EB/OL]. linuxvox.com. https://linuxvox.com/blog/shell‑scripting‑define‑bin‑bash/
[47] Karlsson L. Shebang Shenanigans[EB/OL]. https://linuskarlsson.se/blog/shebang‑shenanigans/
[48] Linux Kernel Source. fs/binfmt_script.c[CP/OL]. https://github.com/torvalds/linux/blob/master/fs/binfmt_script.c
[49] FreeBSD Source. sys/kern/imgact_shell.c[CP/OL]. https://github.com/freebsd/freebsd‑src/blob/master/sys/kern/imgact_shell.c
[50] The Open Group. The Open Group Base Specifications Issue 8[S]. https://pubs.opengroup.org/onlinepubs/9799919799/
[51] Linux Documentation Project. Shell Scripting Basics[EB/OL]. https://www.tldp.org/LDP/Bash‑Beginners‑Guide/html/
[M]专著、[S]标准、[J]期刊、[EB/OL]在线资源、[Z]档案资料。
320



被折叠的 条评论
为什么被折叠?



