善用 `history` 指令能讓命令列操作效率成倍提升。本文通過 15 個實例,從基礎顯示到進階參數替換、環境變數控制,全方位解鎖歷史指令威力。
export HISTTIMEFORMAT='%F %T '
history | more
# 輸出範例
1 2024-01-15 10:30:45 systemctl restart nginx
2 2024-01-15 10:31:02 vim /etc/nginx/nginx.conf
按下 Ctrl+R 進入 `(reverse-i-search)` 提示符,輸入關鍵字即時匹配歷史命令,Enter 執行,←/→ 編輯後執行。
(reverse-i-search)`nginx': systemctl restart nginx
history | head -5
# 1 systemctl restart nginx
# 4 vim /etc/nginx/nginx.conf
!4 # 直接執行第 4 條
!ps # 執行最近一條以 ps 開頭的命令
# ps aux | grep nginx
# ~/.bash_profile
HISTSIZE=1000 # 記憶體中保留條數
HISTFILESIZE=2000 # 歷史檔案保留條數
# 重新登入或 source ~/.bash_profile 生效
# ~/.bash_profile
HISTFILE=~/.my_command_history
# 重新登入生效,歷史將寫入自定義檔案
備份歷史:`sz ~/.bash_history` (需安裝 lrzsz)。
export HISTCONTROL=ignoredups
pwd; pwd; pwd; history | tail -3
# 僅顯示一條 pwd
export HISTCONTROL=erasedups
pwd; ls; pwd; history | tail -3
# 第一條 pwd 被第二條 pwd 覆蓋,只保留最新
export HISTCONTROL=ignorespace
ls -l # 前面有空格,不記錄
pwd # 記錄
history | tail -2 # 僅顯示 pwd 和 history
history -c # 僅清空當前會話記憶體歷史
# 完整清除需同時 > ~/.bash_history
cp /etc/nginx/nginx.conf /backup/nginx.conf.bak
vim !!:$ # vim /backup/nginx.conf.bak
vim !^ # vim /etc/nginx/nginx.conf
cp ~/long.txt /very/long/path/file.txt
ls -l !cp:2 # ls -l /very/long/path/file.txt
ls -l !cp:$ # 同上
export HISTSIZE=0
history # 無輸出
export HISTIGNORE="pwd:ls:ls -ltr:clear:history"
pwd; ls; ls -ltr; systemctl status nginx; history | tail -2
# 歷史中無 pwd/ls/ls -ltr,僅有 systemctl 和 history
# 歷史增強配置
export HISTSIZE=5000
export HISTFILESIZE=10000
export HISTTIMEFORMAT='%F %T '
export HISTCONTROL=ignoredups:erasedups:ignorespace
export HISTIGNORE="ls:ll:la:pwd:clear:history:exit:cd:cd .."
shopt -s histappend # 多終端機共享歷史 (追加不覆蓋)
PROMPT_COMMAND="history -a; history -n; $PROMPT_COMMAND" # 即時同步
將上述配置加入 `~/.bashrc` 並 `source ~/.bashrc`,即刻擁有專業級命令列歷史體驗。