How to remove a secret from .zsh_history on Mac
1. The Gotcha: Active Shell History Caching
If you edit ~/.zsh_history in Vim or run sed while an active terminal window is open, zsh will overwrite your changes when that window closes. Zsh maintains an in-memory history buffer and flushes it on exit.
Before editing, tell your active shell to dump or reload history:
# Clear in-memory history in the current shell:
fc -p
# Or close all other terminal windows before editing.
2. Make a Safety Backup
cp ~/.zsh_history ~/.zsh_history.bak
3. Remove the Leaked Line with sed
On macOS, BSD sed requires an explicit empty string argument for in-place editing:
# Delete any line matching your secret token:
sed -i '' '/ghp_your_secret_token_here/d' ~/.zsh_history
If you have extended zsh history enabled (EXTENDED_HISTORY), lines look like : 1726470000:0;export KEY=.... The sed pattern above matches anywhere on the line, including after the timestamp semicolon.
4. Reload History in Your Shell
Once edited, reload the cleaned file into your current session:
fc -R ~/.zsh_history
Verify the secret is gone:
grep -i "your_secret" ~/.zsh_history