跳转到主要内容
kitlocal.dev

Bash 速查表

本地运行

100% 在你的浏览器中处理。输入和输出绝不会离开你的设备。

GNU Bash 脚本编写与交互快捷键:参数展开、数组、循环、条件判断、重定向以及在 Bash 5.3 上验证的作业控制。

工作原理

Bash parses a line in phases: expansions ($var, $(cmd), globs) happen before the command runs, and whitespace splits unquoted expansions into separate words. Double-quoting "$var" keeps spaces intact while still expanding variables; single quotes disable all expansion.

生存指南

最先需要掌握的少数几个命令。

41 条命令

键盘快捷键/聚焦搜索框JK移动选择C复制选中命令F收藏选中项Esc清空搜索

Script safety & quoting

Start scripts with strict error checking and quote variable expansions to prevent silent failures.

官方文档:The Set Builtin
  • 基础必备

    Exit on errors, unset variables and failed pipeline commands.

    set -euo pipefail

    适用场景

    Prevents scripts from charging ahead after an earlier failure or blank variable expansion.

    命令解析

    -e
    exit immediately when a command returns non-zero
    -u
    treat referencing an unset variable as an error
    -o pipefail
    fail a pipeline if any stage fails, not just the last

    示例

    Place `set -euo pipefail` at the top of scripts to fail fast with exit code 1.

    bash -c 'set -euo pipefail; echo "$UNSET_VAR"'

    运行结果

    bash: line 1: UNSET_VAR: unbound variable

    注意事项

    • Guard commands expected to return non-zero (like grep with no matches) with `|| true` or an `if` check.

    另请参见

Variables & parameter expansion

Use ${...} parameter expansions for defaults, slicing and path stripping without spawning external tools.

官方文档:Shell Parameter Expansion

Conditionals & tests

Prefer [[ ... ]] over [ ... ] in Bash scripts: it avoids word splitting and supports regex matching with =~.

官方文档:Conditional Constructs

Loops & safe file reading

Never parse `ls` in a `for` loop. Use globs for filenames and `while IFS= read -r` for lines.

官方文档:Looping Constructs

Redirection, pipes & process substitution

FD 1 is stdout (normal output), FD 2 is stderr (errors). Order matters when combining them.

官方文档:Redirections

Functions, shortcuts & job control

Use readline shortcuts in your terminal and background/foreground jobs for long tasks.

官方文档:Job Control

在 KitLocal 工具中试用

术语表
Word splitting
Unquoted $var expansions split on spaces/tabs/newlines (IFS), breaking filenames with spaces.
Exit status ($?)
Integer 0..255 returned by the last command. 0 means success; any non-zero value means failure.
Parameter expansion
Transforming variables inside ${...} without spawning sed/awk subprocesses.
Subshell
A child shell created by (...) or pipes where variable changes do not affect the parent shell.