萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 伺服器教學

Linux history 指令 15 大實戰技巧:時間戳、反向搜尋、快速重跑、參數替換、忽略特定命令

善用 `history` 指令能讓命令列操作效率成倍提升。本文通過 15 個實例,從基礎顯示到進階參數替換、環境變數控制,全方位解鎖歷史指令威力。

1. 顯示時間戳:`HISTTIMEFORMAT`

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

2. 反向搜尋:Ctrl + R (神技)

按下 Ctrl+R 進入 `(reverse-i-search)` 提示符,輸入關鍵字即時匹配歷史命令,Enter 執行,←/→ 編輯後執行。

(reverse-i-search)`nginx': systemctl restart nginx

3. 四種重跑上一條命令的方法

  1. ↑ + Enter
  2. `!!` + Enter
  3. `!-1` + Enter
  4. Ctrl + P + Enter (Emacs 風格)

4. 執行指定編號命令:`!n`

history | head -5
# 1 systemctl restart nginx
# 4 vim /etc/nginx/nginx.conf
!4  # 直接執行第 4 條

5. 關鍵字前綴執行:`!string`

!ps  # 執行最近一條以 ps 開頭的命令
# ps aux | grep nginx

6. 控制歷史記錄條數:`HISTSIZE` / `HISTFILESIZE`

# ~/.bash_profile
HISTSIZE=1000        # 記憶體中保留條數
HISTFILESIZE=2000    # 歷史檔案保留條數
# 重新登入或 source ~/.bash_profile 生效

7. 自定義歷史檔案位置:`HISTFILE`

# ~/.bash_profile
HISTFILE=~/.my_command_history
# 重新登入生效,歷史將寫入自定義檔案

備份歷史:`sz ~/.bash_history` (需安裝 lrzsz)。

8. 剔除連續重複:`HISTCONTROL=ignoredups`

export HISTCONTROL=ignoredups
pwd; pwd; pwd; history | tail -3
# 僅顯示一條 pwd

9. 剔除全局重複:`HISTCONTROL=erasedups`

export HISTCONTROL=erasedups
pwd; ls; pwd; history | tail -3
# 第一條 pwd 被第二條 pwd 覆蓋,只保留最新

10. 忽略特定命令 (空格前綴):`HISTCONTROL=ignorespace`

export HISTCONTROL=ignorespace
 ls -l      # 前面有空格,不記錄
pwd        # 記錄
history | tail -2  # 僅顯示 pwd 和 history

11. 清空所有歷史:`history -c`

history -c  # 僅清空當前會話記憶體歷史
# 完整清除需同時 > ~/.bash_history

12. 參數替換:`!!:$` `!^` `!cmd:n`

  • `!!:$`:上一條命令的**最後一個參數**。
  • `!^`:上一條命令的**第一個參數**。
  • `!cmd:n`:歷史中最近以 `cmd` 開頭命令的**第 n 個參數**。
  • `!cmd:$`:同理最後一個參數。
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:$     # 同上

13. 禁用歷史記錄:`HISTSIZE=0`

export HISTSIZE=0
history  # 無輸出

14. 忽略特定命令模式:`HISTIGNORE`

export HISTIGNORE="pwd:ls:ls -ltr:clear:history"
pwd; ls; ls -ltr; systemctl status nginx; history | tail -2
# 歷史中無 pwd/ls/ls -ltr,僅有 systemctl 和 history

15. 組合最佳實踐 (.bashrc 推薦配置)

# 歷史增強配置
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`,即刻擁有專業級命令列歷史體驗。

copyright © 萬盛學電腦網 all rights reserved