851

In the GNU bash shell, I can type Ctrl + R to search for a matching command previously run. E.g., if I type Ctrl + R and then "grep", it lists my last grep command, and I can hit Enter to use it.

This only gives one suggestion though. Is there any way to cycle through other previously typed matching commands?

CC BY-SA 4.0
0

4 Answers 4

1142

If I understand the question correctly you should be able to cycle through alternatives by repeatedly hitting Ctrl + R.

E.g.:

  • Ctrl + R
  • grep
  • Ctrl + R
  • Ctrl + R ...

That searches backwards through your history. To search forward instead, use Ctrl + S, but you may need to have set: stty -ixon (either by .bash_profile or manually) prior to that to disable the XON/XOFF feature which takes over Ctrl + S. If it happens anyway, use Ctrl + Q to re-enable screen output (More details here.)

CC BY-SA 4.0
10
370

If you feel the command will be used frequently, you could add a tag

command #useful

Then

Ctrl + R #useful

This works because # is a comment delimiter, i.e. everything that comes after the symbol is not interpreted as a command. However, it will be recorded in the history and is thus searchable.

CC BY-SA 4.0
8
78

You can also set up the up and down arrows to do a slightly different search by adding these lines to ~/.inputrc:

"\e[A": history-search-backward
"\e[B": history-search-forward

Instead of searching for a substring anywhere in the command (like Ctrl-r) it will search for a command starting with the text to the left of the cursor. For example, if I run these commands:

$ ls bart
$ ls fools

then type ls and press Up twice, it will show ls bart and the cursor in the same place. Compare with Ctrl-r, where it would find the ls twice in the last line, so you'd have to press it once again to find the previous line.

These approaches both have their strengths, and both of them can save a lot of time.

CC BY-SA 3.0
5
33

There's a replacement for built-in Ctrl + R called hstr. It allows to search command history matching all search tokens at the same time (among other things), and cycle through result using arrow keys:

Example

Here's is a demo screencast.

It can be installed on a Debian-family OS like:

add-apt-repository ppa:ultradvorka/ppa
apt-get update
apt-get install hstr

hstr --show-configuration >> ~/.bashrc

And then use Ctrl + R (after reopening the terminal).

CC BY-SA 4.0
3

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.