Shell 教程
Shell 是什么、第一个脚本怎么写、执行方式与退出码。
Key PointsShell 是命令解释器;脚本第一行写 #!/bin/bash,执行要么 chmod +x 后 ./x.sh,要么 bash x.sh。
Shell 是什么
The shell is the command interpreter between you and the kernel. bash is the usual choice on Linux, alongside sh, zsh and fish. Start scripts with #!/bin/bash or #!/usr/bin/env bash, or you will hit syntax differences where /bin/sh is dash.
第一个脚本
Bash
#!/bin/bash
# hello.sh
echo "Hello, Shell!"Bash
cat > hello.sh <<'EOF'
#!/bin/bash
echo "Hello, Shell!"
EOF
chmod +x hello.sh
./hello.sh
bash hello.sh
sh hello.shOutput
Hello, Shell!
Hello, Shell!
Hello, Shell!| Way | Needs +x | Uses shebang | Note |
|---|---|---|---|
./hello.sh | Yes | Yes | Runs with the declared interpreter |
bash hello.sh | No | No | Forces bash |
source hello.sh | No | No | Runs in current shell |
退出码
Bash
echo "ok"
echo $?Output
ok
0Exit code 0 means success; anything else is a failure. && runs the next command only on success, || only on failure, ; always. A script returns the exit code of its last command, or whatever exit N says.
set -euo pipefail is the standard preamble: exit on error (-e), error on unset variables (-u), and fail if any pipeline stage fails (pipefail). Without it, a failing step silently continues.注释与风格
Bash
#!/bin/bash
set -euo pipefail
# 单行注释
: <<'EOF'
这里是多行注释,
用 here-document 加冒号实现。
EOF
readonly LOG_DIR="/var/log/app" # 只读变量
echo "$LOG_DIR"Output
/var/log/appShell 是什么
Shell 是用户和内核之间的命令解释器。Linux 上最常见的是 bash(Bourne Again SHell),还有 sh、zsh、fish。写脚本时用 #!/bin/bash 或 #!/usr/bin/env bash 明确解释器,否则在 /bin/sh 是 dash 的系统上会踩语法坑。
第一个脚本
Bash
#!/bin/bash
# hello.sh
echo "Hello, Shell!"Bash
cat > hello.sh <<'EOF'
#!/bin/bash
echo "Hello, Shell!"
EOF
chmod +x hello.sh
./hello.sh
bash hello.sh
sh hello.shOutput
Hello, Shell!
Hello, Shell!
Hello, Shell!| 方式 | 需要可执行位 | 用 shebang | 说明 |
|---|---|---|---|
./hello.sh | 需要 | 是 | 按声明的解释器运行 |
bash hello.sh | 不需要 | 否 | 强制用 bash |
source hello.sh | 不需要 | 否 | 在当前 shell 执行 |
退出码
Bash
echo "ok"
echo $?Output
ok
0退出码 0 表示成功,非 0 表示失败。&& 前一条成功才执行后一条,|| 失败才执行,; 无条件顺序执行。脚本最后一条命令的退出码就是脚本的退出码,可以用 exit N 显式指定。
set -euo pipefail 几乎是脚本标配:命令失败即退出(-e)、用未定义变量即报错(-u)、管道任一环失败即失败(pipefail)。不加的话,中间一步失败脚本还会继续往下跑。注释与风格
Bash
#!/bin/bash
set -euo pipefail
# 单行注释
: <<'EOF'
这里是多行注释,
用 here-document 加冒号实现。
EOF
readonly LOG_DIR="/var/log/app" # 只读变量
echo "$LOG_DIR"Output
/var/log/app