Shell 教程
核对 Linux Shell 的概念定位、常见 Shell 种类、Shebang(#!)解释器声明,以及可执行程序与解释器参数两种脚本运行机制。
学完这一章,你能够
- 核对 Linux Shell 的概念定位、常见 Shell 种类、Shebang(#!)解释器声明,以及可执行程序与解释器参数两种脚本运行机制。
Shell 的定位与 Shell 脚本概念
Shell 是使用 C 语言编写的系统应用程序,充当用户与操作系统内核之间的交互桥梁,既支持交互式命令解释,也提供完整的脚本编程能力。早期 Unix 由 Ken Thompson 设计了初代 `sh` 命令行外壳,而图形桌面环境(如 Windows Explorer)则属于图形界面形态的 Shell。日常学习既可借助交互式环境练习,也可在本地 Linux 终端或离线容器内直接实测。
Shell 脚本(shell script)是面向 Shell 解释器编写的命令与控制流程序文件。工程讨论中常把“Shell 编程”简称为编写 Shell 脚本,需要区分两个概念:开发 Shell 解释器本身属于系统级 C 程序开发,而本系列聚焦的是基于既有 Shell 编写自动化脚本。
Linux 常见 Shell 环境与 Shebang
编写 Shell 脚本只需文本编辑器与对应的脚本解释器。Linux 生态中常见的 Shell 实现包括 Bourne Shell(`/usr/bin/sh` 或 `/bin/sh`)、Bourne Again Shell(`/bin/bash`)、C Shell(`/usr/bin/csh`)、Korn Shell(`/usr/bin/ksh`)以及部分系统为 root 保留的 `/sbin/sh` 等。
本教程以 GNU Bash(Bourne Again Shell)为核心:它开源免费、功能丰富,也是绝大多数主流 Linux 发行版的默认交互式 Shell。脚本首行的 `#!`(Shebang)用于告知内核应调用哪个解释器来执行该文件;虽然部分发行版中 `/bin/sh` 与 `/bin/bash` 常被混用,但在 Debian 等将 `/bin/sh` 指向 `dash` 的系统中,使用 Bash 扩展语法时应显式写明 `#!/bin/bash` 或 `#!/usr/bin/env bash`。
编写与运行第一个 Shell 脚本
使用 `vi`/`vim` 等编辑器新建脚本文件(习惯以 `.sh` 作为见名知意的后缀,扩展名本身不决定脚本能否运行,若以 PHP 编写则常用 `.php`),在首行写入 `#!/bin/bash` 声明解释器,随后调用 `echo "Hello World !"` 向标准输出打印文本。本站离线 Docker 容器(GNU bash 5.2.15)实测创建 `test.sh` 并赋予执行权限后运行,准确输出 `Hello World !`。
运行 Shell 脚本主要有两种方式。第一种是作为可执行程序:先用 `chmod +x ./test.sh` 添加可执行位,再在所在目录通过 `./test.sh` 启动。必须显式加上 `./` 前缀,因为直接输入 `test.sh` 时系统只会在 `$PATH` 环境变量列出的目录(如 `/bin`、`/sbin`、`/usr/bin`、`/usr/sbin`)中查找,当前目录默认不在 `$PATH` 中;实测不带 `./` 执行返回退出码 `127`(command not found),而 `./test.sh` 返回 `0`。
第二种是作为解释器参数运行,例如 `/bin/sh test.sh` 或 `/bin/php test.php`。采用该方式时脚本文件无需具备可执行权限,且首行 `#!` 声明会被解释器当作普通注释忽略(即便写入无效 Shebang 路径也不影响运行)。实测对 `0644` 权限且带无效 Shebang 的 `noexec.sh` 直接 `./noexec.sh` 返回 `126`,而经 `/bin/sh noexec.sh` 与 `/bin/bash noexec.sh` 均以退出码 `0` 正常输出 `run_via_interpreter`。
运行 GNU bash 5.2 Shebang 可执行脚本、PATH 解析与解释器参数实测
展开查看收起
#!/usr/bin/env bash
set -euo pipefail
export LC_ALL=C.UTF-8
WORKDIR=$(mktemp -d)
trap 'rm -rf "$WORKDIR"' EXIT
VERSION="Debian bookworm-slim GNU bash 5.2.15 (--network none)"
CASES=()
json_str() {
local s="$1"
s=${s//\\/\\\\}
s=${s//\"/\\\"}
s=${s//$'\n'/\\n}
s=${s//$'\r'/\\r}
s=${s//$'\t'/\\t}
printf '"%s"' "$s"
}
add_case() {
local name="$1" summary="$2" expected="$3" actual="$4"
local passed="false"
if [[ "$expected" == "$actual" ]]; then
passed="true"
fi
CASES+=("{\"name\":$(json_str "$name"),\"summary\":$(json_str "$summary"),\"expected\":$(json_str "$expected"),\"actual\":$(json_str "$actual"),\"passed\":$passed}")
}
emit_json() {
printf '{"version":%s,"cases":[' "$(json_str "$VERSION")"
local i
for ((i = 0; i < ${#CASES[@]}; i++)); do
if ((i > 0)); then printf ','; fi
printf '%s' "${CASES[$i]}"
done
printf ']}\n'
}
# Case 1: shebang_hello_script - create executable script with shebang and run via ./test.sh
cat <<'EOF' > "$WORKDIR/test.sh"
#!/bin/bash
echo "Hello World !"
EOF
chmod +x "$WORKDIR/test.sh"
out1=$(cd "$WORKDIR" && ./test.sh)
add_case \
"shebang_hello_script" \
"创建带 #!/bin/bash 的 test.sh 并赋予 +x 权限后通过 ./test.sh 执行输出 Hello World !" \
"Hello World !" \
"$out1"
# Case 2: path_resolution_vs_dot_slash - running bare script name fails when current dir not in PATH
set +e
(cd "$WORKDIR" && test.sh >/dev/null 2>&1)
rc_bare=$?
(cd "$WORKDIR" && ./test.sh >/dev/null 2>&1)
rc_dot=$?
set -e
add_case \
"path_resolution_vs_dot_slash" \
"当前目录默认不在 PATH 中,直接执行 test.sh 返回 127,使用 ./test.sh 返回 0" \
"bare_rc=127;dot_rc=0" \
"bare_rc=${rc_bare};dot_rc=${rc_dot}"
# Case 3: interpreter_arg_no_exec_bit - running via interpreter ignores exec bit and shebang
cat <<'EOF' > "$WORKDIR/noexec.sh"
#!/nonexistent/interpreter
echo "run_via_interpreter"
EOF
chmod 0644 "$WORKDIR/noexec.sh"
set +e
(cd "$WORKDIR" && ./noexec.sh >/dev/null 2>&1)
rc_direct=$?
out_sh=$(cd "$WORKDIR" && /bin/sh noexec.sh)
rc_sh=$?
out_bash=$(cd "$WORKDIR" && /bin/bash noexec.sh)
rc_bash=$?
set -e
add_case \
"interpreter_arg_no_exec_bit" \
"无执行权限且首行 shebang 无效时,直接 ./noexec.sh 返回 126,而作为 /bin/sh 与 /bin/bash 参数可直接运行" \
"direct_rc=126;sh_rc=0;sh_out=run_via_interpreter;bash_rc=0;bash_out=run_via_interpreter" \
"direct_rc=${rc_direct};sh_rc=${rc_sh};sh_out=${out_sh};bash_rc=${rc_bash};bash_out=${out_bash}"
emit_json
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
直接输入 test.sh 时 Shell 仅在 PATH 环境变量包含的目录中搜索可执行文件,当前目录默认不在 PATH 中;./test.sh 显式给出了相对路径(需文件具备 +x 权限并按 Shebang 启动),而 bash test.sh 直接启动解释器并将脚本作为输入文件读取(无需 +x 且忽略 Shebang)。