Thursday, 15 March 2007

Matlab-like interactive search in your Bash command history

You probably already know that to navigate forward and backward in time your command line history, you use arrows. Arrow up: previous command. Arrow down: next command. What if you have to navigate more?



For example, suppose you yesterday looked at a text file. You don't remember its name, but you know you used "cat" to see it. And now you want to see it again. Normally you should have to (a)use the up arrow a lot until you meet the command you wanted or (b)use some trick like cat ~/.bash_history | grep cat and then copy-and-paste the right command.


Good, but it could be better. The science package Matlab for example has a nifty feature that allows you to search in your Matlab command line intelligently, autocompleting the first characters you have typed with matching lines of your command line history. This means that you type "cat" on your command line, by using the up and down arrows you navigate only the history of commands beginning with "cat". A kind of interactive grep on the go. Nice, isn't it?



For some reason this really useful feature is not enabled by default on most Unix distributions I am aware of, but it is really easy to activate it on Bash. Look for a file called .inputrc in your home directory. If you haven't it, look for /etc/inputrc instead (you of course have to be root to edit this one). Open it with your favourite text editor and look for these lines:

"\e[5~": beginning-of-history
"\e[6~": end-of-history

Comment them with a "#" character in front of them:

#"\e[5~": beginning-of-history
#"\e[6~": end-of-history

Insert these lines below the ones you just commented:

"\e[5~": history-search-backward
"\e[6~": history-search-forward

Save and exit. To make the changes have effect you probably have to login again. Now pressing Page-Up and Page-Down should autocomplete the first characters you type with the corresponding commands in the history. Once you get accustomed to this feature, you'll never want to come back.

4 comments:

cornelius said...

Nice. Thanks for the tips. It is quite useful.

Doppelganger said...

In bash, just press Ctrl-r and start typing the pieces of the command that you remember (in this case "cat") and the commands will start showing up right there.

Yigal said...

Any idea how to do this in CSH?

eacousineau said...

Does anyone happen to know that the escape sequences are for the arrow keys Up and Down? I'm having trouble finding them