Search This Blog

Friday, 13 May 2011

Print and Query Command History to Find Specific Past Commands

If you’re trying to remember an exact command you executed via the Terminal but can’t quite come up with it, you can query your command line history to discover old commands by using the following syntax:

history |grep 'search string'

This will look for “search string” in your command history and only print back instances that include the search text. If you’re unfamiliar with the Terminal and you’re wondering why this might be useful, read on for an example.



Example: Searching Past “defaults” Commands

I was trying to recall the exact syntax of a defaults write command that I recently used. The defaults commands are often long strings of text that modify behavior of Mac OS X or certain applications, because of their length and obscurity, trying to remember one of these off the top of your head is challenging to say the least. Instead of hitting the up arrow to scroll through past executions for an eternity, I used the following to narrow my command history to only things with “defaults write” as so:

history | grep 'defaults write'

This passes the results of the extensive ‘history’ command through grep to find only instances that include “defaults write” in the command string, you’ll see a results list that resembles something like this:

$ history |grep 'defaults write'

44 defaults write com.apple.iTunes full-window -1

51 defaults write com.apple.iTunes invertStoreLinks -bool YES

421 defaults write com.apple.FaceTime AutoAcceptInvitesFrom -array-add osxdailycom@gmail.com

426 defaults write com.twitter.twitter-mac ESCClosesComposeWindow -bool true

427 defaults write com.twitter.twitter-mac ESCClosesComposeWindow -bool false

428 defaults write com.apple.appstore ShowDebugMenu -bool true



Now instead of searching through your entire history list, you have narrowed the results.

Refining the Search for Specifics

You can make the history search as specific or unspecific as you want. For example, if I knew the defaults command I was looking for pertained to com.apple.iTunes I could use the following command to further refine my search:

history |grep 'defaults write com.apple.iTunes'

Which would return something like:

44 defaults write com.apple.iTunes full-window -1

51 defaults write com.apple.iTunes invertStoreLinks -bool YES


Try it out yourself. You can do this with any command you’ve entered through the Terminal since all recently executed commands are stored in your history. The defaults command is Mac OS X specific, but history and grep are tools generic to the world of unix, so if you’re ever on a linux machine or otherwise you can use the same techniques.

If you like learning about the underpinnings of Mac OS X, check out our command line tips.