Bash – How to Navigate within bash’s Reverse Search

bashcommand historysearch

Bash offers the functionality to reverse search via Ctrl + R. Then one can type in a part of a command it will show a fitting entry from the history.

Assume this is my history:

vim foo1
vim foo2 # I want to go here
vim foo3 # this is where I land, how to go back?

I search for foo. Hitting Ctrl + R again shows the next fitting search entry. Often it happens to me, that I am too fast and navigate past my intended result and vim foo3 is shown and now I want to go back to vim foo2.

Hence my question is: How do I navigate within the reverse search?

Best Answer

You can access this via the forward-search-history function which is bind per default to ctrl+s. Unfortunately ctrl+s is used to signal xoff per default which means you can't use it to change the direction of the search. There are two solutions for solving the problem, one disabling sending the xoff/xon signaling and the other change the keybinding for forward-search-history

Disable xon/xoff

Run stty -ixon in your terminal or add it to your ~/.bashrc. This allows you to use ctrl+s to use the forward-search-history history function.

For more information about control flow have a look at How to unfreeze after accidentally pressing Ctrl-S in a terminal? and some of the answers

Change the keybinding

If you don't want to change the default behavior of ctrl+s you can change the keybinding for forward-search-history with bind. As most keys are already defined in bash you may have to get creative:

bind "\C-t":forward-search-history

This will bind ctrl+t to forward-search-history, but please be aware that per default ctrl+t runs transpose-chars

Related Question