Navigating Bash History with Ctrl+R

I spend a lot of time at command line, and bash records the history of all the commands I've typed and puts it in .bash_history (there's a limit on how many it stores but for me it goes back a few days). I find it really useful to look back at the history to use the same commands again or edit them slightly. You can press the up arrow to go through your history but it can take a really long time to find what you're looking for. So instead, try Ctrl + r.

To do this: first press Ctrl + r, then start typing the command or any part of the command that you are looking for. You'll see an autocomplete of a past command at your prompt. If you keep typing, you'll get more specific options appear. You can also press Ctrl + r again as many times as you want to, this goes back in your history to the previous matching command each time.

Once you see a command you like, you can either run it by pressing return, or start editing it by pressing arrows or other movement keys. I find this a really useful trick for going back to a command I know I used recently, but which I can't remember or don't want to look up again. I hope this is a useful trick for you too!

8 thoughts on “Navigating Bash History with Ctrl+R

  1. Thanks Lorna, i tried it and it works great. I normally use the command history | grep "" but this is faster i think.

  2. I can never get my head around CTRL-R history enough to use it usefully ... I guess I was used to the 4NT style history with cursor keys in the old days + find it hard to navigate in CTRL-R

  3. Thanks for sharing this. After reading your post I realized that I can edit and run really long command. This definitely saves few keyboard hits and comes handy.
    Regarding running last executed commands there are few more ticks. You can using bang command "!". This doesn't provide you luxury to edit and run. it simply run the command.
    If you type "!find" it will try to run last "find" command. You can write the very first character of command it will find the last executed one and run it again.
    If you want to run just last command executed, run "!!"

  4. Thanks, I was missing that multiple [ctrl]-r could bring you farther back in history. To contribute back some tidbits, a handy command is alias:
    [code]alias l='ls -al'[/code]
    So when you type "l" in console, it automatically does an "ls-al".

  5. nice CTRL-R CTRL-R trick. It keeps searching backwords but once you use movement keys and pick the command how to further do search replace on it ?

Leave a Reply

Please use [code] and [/code] around any source code you wish to share.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>