实战

history                       # 看历史
history 20                    # 最近 20 条
!42                           # 跑历史里第 42 条
!!                            # 跑上一条
!$                            # 上一条的最后一个参数
!ssh                          # 跑最近一条以 ssh 开头的
sudo !!                       # 把上一条加上 sudo

反向搜索(神器)

# 按 Ctrl+R 进入反向搜索
# 输入关键字,Ctrl+R 继续找下一个
# 找到后回车执行,方向键改一下再回车
# Ctrl+G 或 Esc 取消

学会 Ctrl+R 之后用过的命令永不再敲第二遍——这是 shell 老手核心技能之一。

历史文件

~/.bash_history               # bash
~/.zsh_history                # zsh

cat ~/.bash_history | wc -l   # 历史条数

控制历史行为(写进 ~/.bashrc)

# 历史大小
HISTSIZE=10000                    # 内存中保留多少条
HISTFILESIZE=20000                # 文件里保留多少条

# 重复命令只存一条 / 忽略以空格开头
HISTCONTROL=ignoreboth            # = ignoredups + ignorespace

# 多个 shell 共享历史(实时合并)
shopt -s histappend                # 追加而非覆盖
PROMPT_COMMAND="history -a; history -n; $PROMPT_COMMAND"

# 给历史加时间戳
HISTTIMEFORMAT="%F %T  "

之后 history 输出:

1234  2026-05-09 10:23:45  cd /etc
1235  2026-05-09 10:23:50  vim nginx.conf

不想留下的命令

 sudo passwd alice         # 空格开头 → 配 HISTCONTROL=ignorespace 不存历史

或:

unset HISTFILE              # 当前会话整个不存
history -d 123              # 删某条
history -c                  # 清空当前会话历史

在历史里搜索 / 过滤

history | grep ssh          # 找含 ssh 的
history | tail -50          # 最近 50 条
history | awk '{print $2}' | sort | uniq -c | sort -rn | head    # 用得最多的命令

⚠ 安全提示

历史文件会留下你敲过的密码 / token——脚本里 mysql -p mypass 这种风险。

敏感命令

  • 用环境变量传:mysql -p"$MYSQL_PASS"
  • 用配置文件:~/.my.cnf + chmod 600
  • 命令前加空格:HISTCONTROL=ignorespace 时不留历史
  • 重要操作后:history -d <num> 删某条 + history -w 写文件

  • 历史在 shell 退出时才写文件——shell 崩溃前的命令可能丢
  • 多个并行 shell 互相覆盖历史——配 histappend 解决
  • 用 sudo 改了root 的历史不会进当前用户的 ~/.bash_history——找在 /root/.bash_history