Skip to content

Shell 技巧

实用的 Shell 技巧和最佳实践。

历史命令

bash
# 执行上一条命令
!!

# 执行以特定字符开头的上一条命令
!sudo

# 搜索历史命令
Ctrl+R

# 查看历史命令
history

# 清除历史
history -c

进程管理

bash
# 后台运行
command &

# 查看后台任务
jobs

# 调到前台
fg %1

# 暂停进程
Ctrl+Z

# 终止进程
kill -9 PID

重定向

bash
# 输出重定向
command > file.txt

# 追加输出
command >> file.txt

# 错误重定向
command 2> error.txt

# 合并输出和错误
command > all.txt 2>&1

# 丢弃输出
command > /dev/null 2>&1

管道技巧

bash
# 管道传递
cat file.txt | grep pattern

# 多重管道
cat file.txt | grep pattern | wc -l

# tee 命令
command | tee output.txt

# xargs
find . -name "*.txt" | xargs rm

快捷键

快捷键功能
Ctrl+A移动到行首
Ctrl+E移动到行尾
Ctrl+U删除到行首
Ctrl+K删除到行尾
Ctrl+W删除前一个单词
Ctrl+L清屏
Ctrl+C中断命令
Ctrl+D退出 shell
Tab自动补全

别名技巧

bash
# 常用别名
alias ll='ls -la'
alias la='ls -A'
alias l='ls -CF'
alias ..='cd ..'
alias ...='cd ../..'
alias grep='grep --color=auto'

# 安全别名
alias rm='rm -i'
alias cp='cp -i'
alias mv='mv -i'

基于 MIT 许可发布