If you're using iTerm2 on macOS and ran a command that you don't want to appear in your shell history, here’s how you can remove it depending on which shell you're using (most likely zsh or bash):
🔍 Step 1: Identify Your Shell
Run this command to check:
bash
echo $SHELL
/bin/zsh → You're using Zsh
/bin/bash → You're using Bash
🧹 Step 2: Remove the Command from History
✅ For Zsh Users
View your history:
bash
history
Find the line number of the command you want to delete.
Delete the specific line by number:
bash
fc -d <line_number>
Example:
bash
fc -d 123
This will remove it from the in-memory history and the .zsh_history file (depending on your settings).
⚠️ Note: If you don’t want commands saved at all, you can prefix them with a space. In ~/.zshrc, ensure this line exists:
bash
setopt HIST_IGNORE_SPACE
Then any command starting with a space won't be saved.
✅ For Bash Users
View your history:
bash
history
Delete a specific command by line number:
bash
history -d <line_number>
Example:
bash
history -d 123
Save the updated history back to the file:
bash
history -w
💡 To prevent future sensitive commands from being saved, also add a space before the command if HISTCONTROL=ignorespace is set in your environment (common default). You can check with:
bash
echo $HISTCONTROL
📁 Optional: Edit History File Manually
You can edit the history file directly if needed:
Zsh: ~/.zsh_history
Bash: ~/.bash_history
Use a text editor like nano or vim:
bash
nano ~/.zsh_history
# or
nano ~/.bash_history
Then save and exit.
⚠️ After editing, reload the history or restart your shell session for changes to take effect.
🛑 Pro Tip: Prevent Future Sensitive Commands from Being Logged
Add a space before the command:
bash
echo "This won't be saved if ignorespace is set"
Make sure in your shell config (~/.zshrc or ~/.bash_profile) you have:
bash
export HISTCONTROL=ignorespace
Or for Zsh:
bash
setopt HIST_IGNORE_SPACE
Let me know if you'd like help automating cleanup or checking current history settings!