Shell 教程

Shell 是什么、第一个脚本怎么写、执行方式与退出码。

Beginner
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.sh
Output
Hello, Shell!
Hello, Shell!
Hello, Shell!
WayNeeds +xUses shebangNote
./hello.shYesYesRuns with the declared interpreter
bash hello.shNoNoForces bash
source hello.shNoNoRuns in current shell

退出码

Bash
echo "ok"
echo $?
Output
ok
0

Exit 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/app

Friends & Partners