Bash – How to undo changes in the commands-history

bashcommand historyreadline

In UNIX systems you can press top and bottom arrows to navigate through the previous commands. This is extremely handy.

Sometimes, I go up and find a command that I want to use again, but with some variations. If I do such changes, then I don't have a way to get the original command back, unless I check it in history.

Is there any way to "undo" the changes to the command in the history accessed through keys?

My current workaround is to prepend a # to the command. This way the current command is performed as a comment, so nothing happens. Then, I can browse again through the commands with the keys. The problem is that the command I was using may be veeeery far away in the list, so going up again two hundred times is a bit . Control + R is not a solution either, since I may not remember exactly what I was looking for.

Example

I typed the following "50 commands ago":

ls -l /etc/httpd/conf/

Now I went up to that line and changed it to

ls -l /etc/init.d/

but did not press enter. Now, I want to get to the ls -l /etc/httpd/conf/ again.

My environment

$ echo $SHELL
/bin/bash
$ echo $TERM
xterm

Best Answer

As long as you've edited a history entry but not pressed Enter yet, to go back to the original entry, repeatedly press Ctrl+_ — the undo command — until it doesn't make any further change. You're back to the original entry.

Related Question