#!/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
本例需在 本地离线 Docker 容器(debian:bookworm-slim,GNU bash 5.2.15,--network none)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:本地离线 Docker 容器(debian:bookworm-slim,GNU bash 5.2.15,--network none)。
入口文件:projects/linux-shell-lab/explore-shell.sh
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-shell.sh,或下载右侧课程工程包。 - 确认本地已准备 本地离线 Docker 容器(debian:bookworm-slim,GNU bash 5.2.15,--network none)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联32章) · 含当前章节或实例 · mbskycom202612a1487.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1504.zip