Bash History – Search Bash History with Partial + Up-Arrow

bashbashrccommand linehistory

I have searched, but not found anything on this. I am looking for a functionality in bash, using a terminal.

Way back when, I had a user on a debian system, and a friend set me up with a convenient history search feature (I believe I used tcsh then), where I would type the beginning of a previous command, hit up-arrow, and it would do a search, based on the partial string.

E.g. if my history is:

./script.pl
./script.pl arg1
cat output
cat output | grep yada

And I type ., and press up-arrow, it would show me: ./script.pl arg1. Press it again and it would show ./script.pl, etc.

Very much like it would perform a grep on .bash_history. Is there a way to get this functionality?

Best Answer

Open your ~/.inputrc. If you don't have this file, see the end for how to create it. Add these lines:

## arrow up
"\e[A":history-search-backward
## arrow down
"\e[B":history-search-forward

Lines starting with # are comments. I can't remember what is backward and what forward. Experiment with it. Maybe you have to switch backward and forward.

Just re-open possibly open terminal windows for the new behaviour to become effective.


A bit background information:

Bash is using readline to handle the prompt. ~/.inputrc is the configuration file for readline. Note that this will also take effect in other software using the readline library, for example IPython.

Read the bash manual for more information about readline. There you can also find more history related readline commands.

To get the escape codes for the arrow keys you can do the following:

  1. Start cat in a terminal (just cat, no further arguments).
  2. Type keys on keyboard, you will get things like ^[[A for up arrow and ^[[B for down arrow.
  3. Replace ^[ with \e.

For more information about ^[ and \e see here: https://unix.stackexchange.com/a/89817/380515


If you don't already have a ~/.inputrc file, copy the default settings over, or all the other default key bindings will be overridden:

cp /etc/inputrc ~/.inputrc

or begin your ~/.inputrc file with the following line

$include /etc/inputrc

[1]: