# Shebang（Unix）

Shebang 是 Unix 及类 Unix 系统上可执行文本文件开头的字符序列 `#!`，其后跟一个解释器的绝对路径以及一个可选的单一参数；当该文件被执行时，内核会以该脚本作为参数运行所指定的解释器。这一行也被称为 hashbang、hash-pling 或 sha-bang，该机制由内核而非 shell 实现。<sup>[1](https://man.freebsd.org/cgi/man.cgi?manpath=FreeBSD+15.1-STABLE&query=execve&sektion=2)</sup><sup> • </sup><sup>[2](https://osr5doc.xinuos.com/en/man/html.M/exec.M.html)</sup>

| 关键事实 | 详情 |
|---|---|
| 必需形式 | `#!` 必须是文件的前两个字符；`#!` 之后的空格是可选的，解释器路径之后最多只能跟一个参数<sup>[3](https://man.openbsdhandbook.com/script.7/)</sup> |
| 内核机制 | 当把一个解释器文件传给 `execve()` 时，系统实际执行的是解释器，可选参数在前，脚本路径在后<sup>[1](https://man.freebsd.org/cgi/man.cgi?manpath=FreeBSD+15.1-STABLE&query=execve&sektion=2)</sup> |
| 历史 | 第 7 版 AT&T UNIX 中不存在；截至 1981 年 4 月已出现于 4BSD；由 Robert Elz 于 4.2BSD（约 1983 年 9 月）默认实现<sup>[3](https://man.openbsdhandbook.com/script.7/)</sup><sup> • </sup><sup>[4](https://www.in-ulm.de/~mascheck/various/shebang/)</sup> |
| Linux 上的行长限制 | `#!` 之后的文本在 Linux 5.1 之前限制为 127 个字符，自 Linux 5.1 起为 255 个字符；超出部分被忽略<sup>[5](https://man7.org/linux/man-pages/man2/execve.2.html)</sup> |
| 参数 | Linux 将解释器路径之后的所有内容作为一个参数传递；macOS 能正确传递多个参数；Solaris 在第一个参数之后截断<sup>[5](https://man7.org/linux/man-pages/man2/execve.2.html)</sup><sup> • </sup><sup>[3](https://man.openbsdhandbook.com/script.7/)</sup> |
| 可移植性惯用法 | `#!/usr/bin/env interpreter` 使用 `env` 工具在 `PATH` 中搜索解释器；GNU Coreutils 的 `env -S` 可将 shebang 字符串拆分为多个参数<sup>[3](https://man.openbsdhandbook.com/script.7/)</sup><sup> • </sup><sup>[6](https://www.gnu.org/s/coreutils/manual/html_node/env-invocation.html)</sup> |
| 标准化 | POSIX 未规定 `#!` 的行为；LSB 保留了这一构造，并建议首行不超过 80 字节<sup>[5](https://man7.org/linux/man-pages/man2/execve.2.html)</sup><sup> • </sup><sup>[7](https://refspecs.linuxfoundation.org/LSB_4.1.0/LSB-Core-generic/LSB-Core-generic/executable-scripts.html)</sup> |

## 内核如何处理该行

当程序对某个文件调用 `execve()` 时，内核会检查文件开头的几个字节以确定其类型。如果文件以 `#!` 开头，内核的脚本处理程序（在 Linux 中为 `fs/binfmt_script.c`）会将首行剩余部分解析为解释器路径和一个可选参数，然后以解释器替代脚本重新执行该进程。<sup>[8](https://lwn.net/Articles/630262/)</sup><sup> • </sup><sup>[9](https://github.com/torvalds/linux/blob/master/fs/binfmt_script.c)</sup> 解释器收到的参数向量形式为 `interpreter [optional-arg] path arg...`，其中 `path` 是脚本的路径名，`arg...` 是原始 `execve()` 调用中从 `argv[1]` 开始的参数；原始的 `argv[0]` 无法恢复。<sup>[5](https://man7.org/linux/man-pages/man2/execve.2.html)</sup>

解释器路径的执行不查询 `PATH` 环境变量，因此通常必须是绝对路径。<sup>[3](https://man.openbsdhandbook.com/script.7/)</sup> 自 Linux 2.6.28 起，shebang 行上指定的解释器本身也可以是脚本，可递归，最多四层。<sup>[5](https://man7.org/linux/man-pages/man2/execve.2.html)</sup> Linux（与大多数其他现代 UNIX 系统一样）忽略脚本上的 set-user-ID 和 set-group-ID 位，[OpenBSD](https://www.edgepedia.org/zh/openbsd) 的手册记载了内核检查脚本与解释器打开脚本之间的竞态条件，作为 setuid 解释器脚本危险的原因之一。<sup>[5](https://man7.org/linux/man-pages/man2/execve.2.html)</sup><sup> • </sup><sup>[3](https://man.openbsdhandbook.com/script.7/)</sup>

如果文件没有 shebang，`execve()` 会以 `ENOEXEC` 失败。随后 `execlp()` 和 `execvp()` 函数会退回到用命令解释器（`sh`）运行该文件，大多数 shell 在自行尝试执行文件时也采取同样的做法；此行为在内核之外实现，并不保证每个执行其他程序的程序都遵循。<sup>[10](https://pubs.opengroup.org/onlinepubs/9799919799/functions/exec.html)</sup><sup> • </sup><sup>[3](https://man.openbsdhandbook.com/script.7/)</sup>

## 参数与可移植性限制

解释器路径之后文本的处理方式因系统而异，这是 OpenBSD 手册列出的两个可移植性例外之一（另一个是行长）。在 Linux 上，解释器名称之后的整个字符串作为一个参数传递，包括空白字符；其他一些系统在第一个空白字符处终止参数，还有一些系统按空白字符分隔传递多个参数。<sup>[5](https://man7.org/linux/man-pages/man2/execve.2.html)</sup> 具体来说，`#!/bin/interp -x -y` 这一行在 OpenBSD 上产生的参数是单个字符串 `-x -y`，在 Solaris 上只有 `-x`，在较新版本的 Apple OS X 上则分别为 `-x` 和 `-y`。<sup>[3](https://man.openbsdhandbook.com/script.7/)</sup> 实用建议是最多只传一个参数，不要依赖多个参数被拼接。<sup>[3](https://man.openbsdhandbook.com/script.7/)</sup>

行长限制也各不相同。Linux 忽略 `#!` 之后超过 127 个（5.1 之前）或 255 个（自 5.1 起）的字符；OpenBSD 将行限制为 `<sys/param.h>` 中定义的 `MAXINTERP`；[Linux 标准基础](https://www.edgepedia.org/zh/linux-standard-base)建议整个首行不超过 80 字节，且解释器和参数均不得包含引号字符或空白。<sup>[5](https://man7.org/linux/man-pages/man2/execve.2.html)</sup><sup> • </sup><sup>[3](https://man.openbsdhandbook.com/script.7/)</sup><sup> • </sup><sup>[7](https://refspecs.linuxfoundation.org/LSB_4.1.0/LSB-Core-generic/LSB-Core-generic/executable-scripts.html)</sup>

## env 跳板

`env` 工具执行其自身命令行上指定的命令，并在 `PATH` 中搜索它，而 `/usr/bin/env` 几乎存在于所有 POSIX 风格的系统上，这使得该技巧在实践中相当可靠。<sup>[3](https://man.openbsdhandbook.com/script.7/)</sup>

这种惯用法有代价：由于在 GNU/Linux 等系统上内核将 `env` 路径之后的所有内容作为单个参数交给 `env`，像 `#!/usr/bin/env perl -T -w` 这样的行会失败，报错如 `/usr/bin/env: 'perl -T -w': No such file or directory`。<sup>[6](https://www.gnu.org/s/coreutils/manual/html_node/env-invocation.html)</sup> GNU Coreutils 增加了 `-S`（`--split-string`）选项，将该单个字符串拆分为多个参数，因此 `#!/usr/bin/env -S perl -T -w` 可以按预期工作；在 `-S` 之前加上 `-v` 标志可在排查问题时打印字符串的拆分方式。<sup>[6](https://www.gnu.org/s/coreutils/manual/html_node/env-invocation.html)</sup> 在缺少 `-S` 的旧版 macOS 上，通常的变通方法是使用两行的包装脚本代替 shebang。<sup>[11](https://creativecodingtech.com/devops/linux/2026/01/09/linux-shebang-env-s-flag.html)</sup>

`env` 形式还改变了运行哪个解释器：它选取调用者 `PATH` 中第一个匹配的可执行文件，因此用户可以将较新或自定义的解释器放在 `PATH` 中更靠前的位置来选择它。这在 macOS 上是有意为之——系统自带的 Bash 是旧的 3.2 版本，用户会在别处安装当前版本——但当错误的解释器版本会破坏脚本时，这就成了隐患；LSB 指出，执行时 `PATH` 是未知的，可能会选中解释器的另一个版本。<sup>[12](https://www.mironsoft.de/en/blog/bash-shebang-portability-env-bash-versus-absolute-path)</sup><sup> • </sup><sup>[7](https://refspecs.linuxfoundation.org/LSB_4.1.0/LSB-Core-generic/LSB-Core-generic/executable-scripts.html)</sup>

## 历史

`#!` 机制在第 7 版 AT&T UNIX 中并不存在，当时的 shell 将任何以 `ENOEXEC` 执行失败的文件当作 shell 脚本处理。Guy Harris 于 1984 年 10 月 16 日发到 net.unix 的一篇 Usenet 帖子称，这一想法由[贝尔实验室](https://www.edgepedia.org/zh/bell-labs)研究员、Unix 共同创造者 [Dennis Ritchie](https://www.edgepedia.org/zh/dennis-ritchie) 提出，最早的实现是在 BSD 上；历史 exec 手册页显示，截至 1981 年 4 月，该行为已出现于 4BSD。<sup>[3](https://man.openbsdhandbook.com/script.7/)</sup> 4.0 BSD 源文件 `sys/sys1.c` 中引用了 Dennis Ritchie 介绍该特性的一封旧邮件，该特性由[墨尔本大学](https://www.edgepedia.org/zh/university-of-melbourne)系统程序员 Robert Elz 于 1983 年 9 月前后在 4.2BSD 上默认实现；该实现将所有 `#!` 参数作为单个参数传递。<sup>[4](https://www.in-ulm.de/~mascheck/various/shebang/)</sup> 在 4.3BSD Net/2 中，该代码在许可证纠纷期间被移除，不得不为 NetBSD 和 386BSD 等后继系统重新实现。<sup>[4](https://www.in-ulm.de/~mascheck/various/shebang/)</sup>

POSIX 从未规定该行为：该构造在 POSIX 1003.1-2001 中未定义但被保留，OpenBSD 手册指出 IEEE Std 1003.1-2004 仅间接提及它，尽管 System V 接口定义第四版对其有部分描述。<sup>[7](https://refspecs.linuxfoundation.org/LSB_4.1.0/LSB-Core-generic/LSB-Core-generic/executable-scripts.html)</sup><sup> • </sup><sup>[3](https://man.openbsdhandbook.com/script.7/)</sup>

## 相关机制与用途

Linux 的 `binfmt_misc` 设施推广了这一想法：管理员可以注册任意文件格式，通过魔数字节匹配，经由选定的解释器运行，并用标志控制参数处理、凭证和文件描述符传递。<sup>[13](https://docs.kernel.org/admin-guide/binfmt-misc.html)</sup>

包管理和环境系统会在安装时重写 shebang 行。Python 虚拟环境安装的脚本，其 shebang 包含指向该环境解释器的绝对路径，如 `#!/<path-to-venv>/bin/python`，因此脚本无论 `PATH` 如何都会用该解释器运行；这使得这些环境本质上不可移植。<sup>[14](https://docs.python.org/3/library/venv.html)</sup> Nix 的 `patchShebangs` 函数将 `#!/usr/bin/env python` 重写为构建所选解释器在 Nix 存储中的确切路径，确保总能找到正确的解释器。<sup>[15](https://github.com/NixOS/nixpkgs/blob/master/doc/stdenv/stdenv.chapter.md)</sup> Python 的打包指南鼓励分发者在打包第三方脚本时，将不够具体的 shebang（如 `python`）改为更具体的（如 `python3`）。<sup>[16](https://peps.python.org/pep-0394/)</sup>

## References

1. [execve(2), FreeBSD 15.1-STABLE Manual Pages](https://man.freebsd.org/cgi/man.cgi?manpath=FreeBSD+15.1-STABLE&query=execve&sektion=2)
2. [exec(m)](https://osr5doc.xinuos.com/en/man/html.M/exec.M.html)
3. [script(7), OpenBSD Handbook Manuals](https://man.openbsdhandbook.com/script.7/)
4. [The #! magic, details about the shebang/hash-bang mechanism, Sven Mascheck](https://www.in-ulm.de/~mascheck/various/shebang/)
5. [execve(2), Linux manual page](https://man7.org/linux/man-pages/man2/execve.2.html)
6. [env invocation, GNU Coreutils 9.11 manual](https://www.gnu.org/s/coreutils/manual/html_node/env-invocation.html)
7. [Executable Scripts, Linux Standard Base Core Specification 4.1](https://refspecs.linuxfoundation.org/LSB_4.1.0/LSB-Core-generic/LSB-Core-generic/executable-scripts.html)
8. [Kernel development: binfmt_script, LWN.net](https://lwn.net/Articles/630262/)
9. [linux/fs/binfmt_script.c, Linux kernel source](https://github.com/torvalds/linux/blob/master/fs/binfmt_script.c)
10. [exec, POSIX.1-2024, The Open Group](https://pubs.opengroup.org/onlinepubs/9799919799/functions/exec.html)
11. [env: 'foo bar': No such file or directory, Creative Coding Tech](https://creativecodingtech.com/devops/linux/2026/01/09/linux-shebang-env-s-flag.html)
12. [Shebang Portability: env bash vs. an Absolute Path, mironsoft.de](https://www.mironsoft.de/en/blog/bash-shebang-portability-env-bash-versus-absolute-path)
13. [Kernel Support for miscellaneous Binary Formats (binfmt_misc), Linux Kernel documentation](https://docs.kernel.org/admin-guide/binfmt-misc.html)
14. [venv, Creation of virtual environments, Python 3 documentation](https://docs.python.org/3/library/venv.html)
15. [patchShebangs, nixpkgs stdenv chapter](https://github.com/NixOS/nixpkgs/blob/master/doc/stdenv/stdenv.chapter.md)
16. [PEP 394, The "python" Command on Unix-Like Systems](https://peps.python.org/pep-0394/)

---
*Initially written Sep 17, 2026 · Reviewed: Sep 19, 2026; Oct 15, 2026 · Edited: Sep 19, 2026; Oct 15, 2026 · Last review: Oct 15, 2026*

Topic: 技术与人造世界 › 计算技术与数字系统 › 软件与编程 › Operating systems › Unix-like and Linux › Unix, BSD, and kernel internals

Copyright 2026 Edgepedia

License: Edgepedia Community License 1.0, https://www.edgepedia.org/edgepedia/license

Source: https://www.edgepedia.org/zh/shebang-unix

English original: https://www.edgepedia.org/shebang-unix
