Terminal: Searching Your Command History

If you use the Terminal for troubleshooting, you probably know that you can press the Up Arrow key to see your recently used commands. At the prompt, you'll just keep tapping that key until you see the command you'd like to execute again, and then press Return.

Apparently, that was the last command I used. Now if only I had any memory of why I needed to do that.

Anyway, that sure is a groovy way to avoid retyping a lot of stuff, but did you know that you can actually search through the commands you've typed instead of just looking through your history? So if you remember, for example, that you ran a defaults write command a while back but don't know what it was, you can search through Terminal to find it. Here's how. First, open the program (it's in Applications> Utilities), and at the prompt, press the keyboard shortcut Control-R. That'll turn your prompt from this…

…into this:

Then you'll type in a search for the command you're hoping to find. If you were looking for that defaults write one, you could search for "defaults," "write," or even a string from within a word, such as "fault." Cool! In the screenshot below, I've searched for sudo:

As you type, it'll show you the last command you executed that matches your search. To see more results, press Control-R repeatedly, and it'll step back through your history. When you find the command you're looking for, press Return to run it again.

Also, if you'd like to exit the search without doing anything, press Control-G (or Command-Period, if you like that better), and you'll be back at your regularly scheduled prompt. This tip has saved me so much time that it's a little unbelievable. My typing teacher would probably scold me for relying too much on shortcuts, wouldn't he?