Bash 歷史記錄分佈於記憶體緩衝區、磁碟檔案(~/.bash_history)與全域設定(/etc/profile)三個層面,徹底清除需分別處理。
編輯 /etc/profile(全域)或 ~/.bashrc(單用戶),將 HISTSIZE 設為 0 或 1:
# /etc/profile 或 ~/.bashrc
export HISTSIZE=0
export HISTFILESIZE=0
生效方式:重新登入或執行 source /etc/profile。設為 0 即完全不記錄;設為 1 僅保留最後一條指令(便於除錯)。
history -c
此指令僅清除當前 Shell 實例的記憶體內歷史清單,不影響磁碟上的 ~/.bash_history。
rm -f ~/.bash_history
下次登入時 Bash 會自動建立新的空白歷史檔。
Bash 預設在 Shell 正常退出時才將緩衝區寫入 ~/.bash_history。若需立即落盤(例如清除後想確保不殘留),執行:
history -w
配合清除流程:
history -c # 清空記憶體
history -w # 寫入磁碟(此時寫入空清單)
rm -f ~/.bash_history # 徹底刪除檔案
在指令前加空白鍵(需設定 HISTCONTROL=ignorespace 或 ignoreboth):
sensitive-command-with-password
export HISTIGNORE="ls:cd:cd *:pwd:history:exit:clear"
export HISTTIMEFORMAT="%F %T "
# ~/.bashrc
shopt -s histappend
PROMPT_COMMAND="history -a; history -c; history -r; $PROMPT_COMMAND"
HISTCONTROL=ignorespace:erasedups 並定期清理。auditd 或 syslog 記錄完整指令上下文,而非依賴 Bash 歷史。掌握 HISTSIZE、history -c、history -w 三者關係,即可精準控制歷史記錄的保留與清除。配合 HISTIGNORE、HISTCONTROL 等環境變數,能在便利性與安全性間取得最佳平衡。