Ctrl-r

2022-02-28 13:24:40 +0100 +0100

The single most useful command in my toolbox is Ctrl-r.

I’m often surprised how many people don’t use it, so here’s a brief post about what it is and why you might want use it.

🧰 What it does

In a bash shell, typing “Control” and “r” together drops you into a prompt:

$
(reverse-i-search)`':

Once you’re in the prompt, start typing characters to do a reverse search through your shell command history:

If you don’t see the result that looks correct, press Ctrl-r again to cycle through results that were found. Press Enter to run the selected command or Ctrl-a / Ctrl-e to go get to your bash prompt with the command written out, and with your cursor at the beginning or end of the command.

🤔 Why

As software engineers we have too many things to remember.

I prefer to not spend time memorizing command line tool argument order, values, or syntax—is it “foo –type=bar” or “foo –type bar” or “foo bar”, or “TYPE=bar foo”?

With Ctrl-r I don’t have to think about these things.

It’s true that well-written command line tools have shell completion scripts to facilitate autocompletion. I use these for exploring a command, but I find in my day-to-day work, I’m almost always running the same scripts or slight variations on them. But for example, I have no need or desire to type out by hand commands like rm src/LocalSettings*; docker run -it --rm --workdir=/workspace/src --env-file=.env -v ~/workspace/cache:/cache -v ~/workspace/log:/log -v ~/workspace/ref:/srv/git:ro -v ~/workspace/src:/workspace/src quibble --packages-source=composer --skip-zuul --db sqlite --skip api-testingz --web-backend=php.

I just use Ctrl-r to get back to doing more interesting things. If the command doesn’t exist in my history, then I do the work of figuring out the correct invocation once, and then can access it quickly any time I need it again in the future.

💡 Tips


  1. There is of course a Rust port, haven’t tried it yet though. ↩︎