Shell Tricks That Actually Make Life Easier (And Save Your Sanity)
来源: Larvitz Blog / Christian Hofstede-Kuhn | 日期: 2026-03-26 原文: Shell Tricks That Actually Make Life Easier 精读日期: 2026-03-28
一句话总结
那些 shell 老手习以为常、新人却从没人教过的终端快捷键和技巧——从 1989 年就存在,但大多数人还在用退格键一个字一个字删。
核心内容
一、全平台通用(POSIX shell / 任意 SSH 环境)
光标移动 & 编辑
| 快捷键 | 作用 |
|---|---|
Ctrl+W |
删除光标前整个单词 |
Ctrl+U / Ctrl+K |
剪切到行首 / 行尾 |
Ctrl+Y |
粘贴(yank,配合 U/K 使用) |
Ctrl+A / Ctrl+E |
跳行首 / 行尾 |
Alt+B / Alt+F |
按单词跳转(Mac 需开 Option as Meta) |
Ctrl+L |
清屏(不打断当前输入) |
终端急救 - reset /
stty sane:cat 了二进制乱码后盲敲救命 -
Ctrl+C:终止命令;Ctrl+D:EOF / 空提示符时退出
shell(注意区分)
目录导航 - cd -:两目录之间来回横跳 -
pushd / popd:多目录栈管理
脚本防错(必加在 shebang 后) -
set -e:遇错退出(有边界情况,别盲信) -
set -u:未定义变量报错,防止
rm -rf /prefix/${TYPO}/* 类灾难 -
推荐组合:set -euo pipefail
其他 -
> file.txt:清空文件不删除(保留权限、不中断持有文件的进程)
- $_:上条命令的最后一个参数,如
mkdir -p /long/path && cd "$_"
二、Bash / Zsh 专属
历史搜索 -
Ctrl+R:反向搜索历史,按住继续往前翻
命令复用 -
!!:展开为上条命令全文,sudo !! 是最经典用法 -
ESC + . /
Alt + .:插入上条命令的最后一个参数,可重复按往前追溯 -
!$:同上但非交互式(回车时盲展开,脚本里改用
$_)
编辑器转义 -
Ctrl+X, Ctrl+E:把当前输入扔进 $EDITOR
全力编辑,保存即执行(Zsh 需配置) - fc:打开上条命令到
$EDITOR,可移植性更好,多 shell 通用
花括号展开
cp pf.conf{,.bak} # → cp pf.conf pf.conf.bak
mv filename.{txt,md} # → mv filename.txt filename.md
mkdir -p project/{src,tests,docs} # 批量建目录进程替换
diff <(sort file1.txt) <(sort file2.txt) # 无需临时文件递归 glob
shopt -s globstar # Bash 需要手动开;Zsh 默认开
ls **/*.js # 递归匹配所有子目录后台脱壳三连(忘开 tmux 的救命)
Ctrl+Z → bg → disown
进程从 shell 剥离,SSH 断了照跑
日志同步输出
command |& tee file.log # stdout + stderr 同时屏显 + 写文件
# 等价于 command 2>&1 | tee file.log金句摘录
- “The terminal becomes a place we live in—but we rarely bother to arrange the furniture.”
- “Once you get used to this, holding Backspace feels like digging a hole with a spoon.”
- “Pick just one trick, force it into your daily habits for a week, and then pick another. Stop letting the terminal push you around, and start rearranging the furniture. It’s your house now.”
Justin 视角
这篇文章对你的直接价值在于日常 Claude Code 操作效率,不是投资判断。几个具体场景:
Ctrl+X, Ctrl+E:在 CC prompt 里写长指令时直接跳 vim 改,比在终端行内盲改省心很多set -euo pipefail:CC 生成 shell 脚本时可以要求它默认加这个头,防止脚本中途失败还继续跑|& tee:调试 CC 跑的长任务时,stdout + stderr 同步写日志,方便事后排查- 花括号展开:备份配置文件
cp config.json{,.bak}这个习惯值得养成,之前你在 Infra 里改配置就踩过没备份的坑 fc:比Ctrl+X,Ctrl+E更通用,Bash/Zsh/ksh 都能用,记这个够了
文章深度一般(是个整理帖,不是原创洞见),但作为工具参考价值不低,建议收藏备查。
延伸阅读
- readline 官方文档(Emacs binding 出处)
man bashHISTORY EXPANSION 章节- zsh globbing 文档:
zshexpn(1)