history
command shows all the results but we can filter to get particular command using history | grep searchingCommand
. It is really helpful.
But the problem is it shows those commands also which was entered with typo error or which was unsuccessful. Then identifying the correct one is really a pain. I checked this link: Selective command-history in the terminal? but that was not my solution.
So is there a way to delete those commands from the history which was incorrect at the time entered or later?
Best Answer
I'd like to add another method of modifying (or deleting) history entries, which I found rather accidentally when I was working with the bash:
To demonstrate this, start by executing the following three commands in bash:
You can now select these commands again using the arrow keys or Ctrl+p and Ctrl+n.
Say you want to modify the first two commands. Move through history until
echo 1
appears and change it toecho 1 - changed
, but DO NOT PRESS ENTER. If you now move further through your history, this line stays in its modified state and you can move away from and back to it. Now move to the lineecho 2
and change it toecho 2 - changed
, again don't press enter. In order to save the changes to these lines, select any command in history except for these two, and hit Ctrl+c.Of course, instead of modifying the history entry, you may also remove it which will result in an empty line at that entry. To delete the line currently displayed at the prompt, hit Ctrl+e (which jumps to the end of the line) followed by Ctrl+u (which deletes the text from the start of the line to the cursor).
See also https://unix.stackexchange.com/questions/195668/what-can-cause-an-item-to-be-deleted-from-my-bash-history/195726#195726 for a more detailed explanation of the technical background.
Simplest Way:
Note:
This changes only the current session commands. If we want to change older commands and save the changes we need to run following command before closing the terminal: