Better command history browsing in Terminal

29.01.2010
Today's hint is for those who spend a fair bit of time in Terminal. If you do, you're probably aware that Terminal tracks your command history--that is, it keeps a record of the commands you've used, and you can scroll through those historical commands. Press the Up Arrow key from the command prompt, and you'll see the most-recently used command; each additional press moves further back through history, and the Down Arrow key moves forward in the history file.

There are a couple tricks to getting even more out of this history file, though. First, you can search through it by pressing Control-R to bring up the (reverse-i-search) prompt. Once the prompt appears, enter a portion of the command name you'd like to find, ssh for instance, and then just keep pressing Control-R to see each match in the history file. When the one you want to re-use appears, press Return to execute the command.

While this is nice, it's a bit of a pain to press Control-R. So another option, and the focus of this hint, is to give the Up Arrow and Down Arrow keys another role: they'll do what Control-R does, but only when you've already started typing a command.

So in normal use, if you haven't started typing a command, the Up Arrow key will show the last-used command. But if you start typing a command, then the Up Arrow key will actually run a search of the command history, and show the last-used command that begins with the letters you've already typed. (This is subtly different than Control-R, which finds the string you've typed anywhere within a previously-used command. I think this difference, though, actually makes this hint more useful.)

To make this work, you need to edit your user's .profile file, which is in the top level of your user's folder. Open Terminal, and type nano .profile. If you have an existing file, it will open for editing; otherwise, you'll see a blank screen.

Add these two lines to the file, but note you can't copy and paste these lines, as there are special characters in there (which I'll explain how to enter).