Search in History

No, this post was not meant for historians. It is for Linux terminal users... Well, in this era of glittering user interfaces, I suppose the latter kind can be considered as historians, eh?

No matter who you are, if you are using Linux terminals, you should be familiar with bash shell, which is around since 1989, indisputably the most used Linux shell in-universe ( I am pretty sure if there are aliens out there, and if they are using Linux, then they must be using bash shell, too).

If you use bash shell actively, you would know that bash keeps a history of entered lines. And if you perform some repetitive tasks on the console, that history comes very handily.

First of all, you may list your history:

$ history
    1 ping www.google.com
    2 cat /etc/hosts
    3 sudo apt-get update
    4 sudo apt-get install tree
    5 cat /etc/inputrc

As you see, history command lists everything you typed on your console, since the beginning of time... or the beginning of bash, precisely.

Bash provides two ways to search something in history. One is ready to use by default, and the other is not.

First one is reverse-i-search, in other words, reverse intelligent search method, which you can directly invoke by pressing CTRL + r at Linux terminal.

(reverse-i-search)`': _

When you start to type in that prompt, your input will be used as a keyword to return first matching line in your history. It will return newest lines first, but you can continue for older lines by pressing CTRL + r again and again. After you find what you want, you may press ENTER to execute it, or you may press End or Home to edit it.

The second one, which is my preference, is disabled by default. You should either tinker with /etc/inputrc file, to enable it for all users in your system, or create a local .inputrc file in your home folder, to enable it just for yourself.

$ vim ~/.inputrc

In order to use cursor up and down keys for history search, add following two lines to your .inputrc file:

"\e[A" : history-search-backward
"\e[B" : history-search-forward

To see your changes in action, it's best to restart your bash session, either by giving bash command on the shell or starting a new terminal.

With this feature active, when you start typing a command on your bash prompt, you can use cursor up/down keys to browse all matching lines from your history. If you want to narrow results, type more, then try again.

These nice features in bash actually come from readline library, and you can actually use them in your own terminal-like applications, with a proper use of this library.

When it comes to bash, there is much more to it than meets the eye. So consider this as a basic history post.