Monday, March 28, 2016

How to Enable Search History Feature with Bash

Assume your ~/.bash_history file has the following content:
gcc test.c
gcc -g test.c
cat test.c
vim test.c
ssh root@localhost
ssh root@192.168.1.1
g++ test.cpp
g++ test.cxx

Now, say you type
$ gcc[up arrow]

Normally, the [up arrow] key will simply give you the last command, that is
$ g++ test.cxx

However, this is quite annoying. When you type gcc first and pressing the [up arrow] should intuitively tell bash to search for all the previous commands starting with gcc. What you probably expected was
$ gcc -g test.c
or
$ gcc test.c

Well, there is a way to do this. Edit your ~/.bashrc file and add the following lines:
bind '"\e[A": history-search-backward'
bind '"\e[B": history-search-forward'

NOTE: if you are on Mac OS X, append the above two lines to ~/.bash_profile instead.

Save the file and exit bash. Now when you restart bash, you should see search history feature enabled. That is, when you type
$ gcc[up arrow]
will show you
$ gcc -g test.c

Another [up arrow] will show you
$ gcc test.c

Similarly, typing
$ ssh[up arrow]
will show
$ ssh root@192.168.1.1

One more [up arrow] will yield
$ ssh root@localhost

No comments:

Post a Comment