How to remove a single line from history?
Preventative measures
If you want to run a command without saving it in history, prepend it with an extra space
prompt$ echo saved
prompt$ echo not saved \
> # ^ extra space
For this to work you need either ignorespace
or ignoreboth
in HISTCONTROL
. For example, run
HISTCONTROL=ignorespace
To make this setting persistent, put it in your .bashrc
.
Post-mortem clean-up
If you've already run the command, and want to remove it from history, first use
history
to display the list of commands in your history. Find the number next to the one you want to delete (e.g. 1234) and run
history -d 1234
Additionally, if the line you want to delete has already been written to your $HISTFILE (which typically happens when you end a session by default), you will need to write back to $HISTFILE, or the line will reappear when you open a new session:
history -w
To clear all your history, use
history -c
To delete a single line, use
history -d linenumber
I have this in my ~/.bashrc
, which makes the command $ forget
delete the previous command from history
function forget() {
history -d $(expr $(history | tail -n 1 | grep -oP '^ \d+') - 1);
}