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
- The UX of
Ctrl
-r
is improved immeasurably by the fzf plugin. It works withbash
,zsh
,fish
. Highly recommended! 1 It does other fancy things too, like finding files in subdirectories. - I’ve tried to stop using
cd
. I just useCtrl
-r
and type a few characters of the directory I want to go to. For example, if I want to navigate to~/src/mediawiki/w/extensions/GrowthExperiments
, I can typeCtrl
-r
,gr
, thenCtrl
-p
(to go up in the command history) until I get to the relevant entry. When I do usecd
, it’s to get an entry into my shell history, so I usecd /full/path
instead of a relative path. - with bash, you may run into issues where one terminal tab doesn’t have access to history of commands run in another tab. Probably better to use a shell like
zsh
orfish
.