Tip of the Day: Reverse Search in Bash and Power Shell

If you use Bash (or, yes, Power Shell on Windows) with any regularity, there are probably a number of commands you repeat frequently. While you could alias these commands to shorter snippets, that doesn't always scale well. There are many other options available to make your life a little simpler; one of my personal favourites is reverse search. When you use the keyboard combination ctrl + r, you can begin typing to search your bash history in real-time, for the most recent command which matches what you're typing.

ctrl + r

A quick example: I currently use bash through a Cygwin wrapper on Windows and my SSH sessions are only maintained while a terminal window is open. Each time I open a new terminal, I have to reinitialize an SSH session and add whichever SSH key(s) I'm planning to use. This means I end up typing something, along the lines of the following, dozens of times per day:

ssh-add ~/.ssh/someKeyFile

It's not a particularly long command to type out, but in volume it's an annoyance--especially when I only have to do it because I accidentally closed a terminal window. Instead of typing this out in full each time, I just hit ctrl + r and type in ssh- (just enough to match this, and not another ssh-based command). As I'm typing, the most recent bash history item to match my search is displayed. When I see the one I want, I simply hit enter and viola! it runs again. If the most recent match isn't the one I want (in this example, I might be looking to add a different SSH key file than the last one I added), I can jump to older matches by simply hitting ctrl + r again.

The other scenario I frequently use this short-cut for is when I need to repeat a command I can't quite remember, but I remember part of, and know I've run it before. This is a great time-saver over having to up-arrow through every history item.

And yes, this does also work in Windows Power Shell (but not in CMD).