Linux: ZSH-style up/down arrows in Bash/Readline

📄 Wiki page | 🕑 Last updated: Aug 22, 2022

Searching through history with an up/down arrow key is a very popular (and very useful) feature in ZSH.

What many people don't know is that you can enable similar behavior in Bash simply by adding these lines to your ~/.inputrc file:

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

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

When you press the up/down arrow key ("\e[A"/"\e[B"), Readline will call the history-search-backward/history-search-forward command, which will search (in the backward or forward direction) through the history for the string of characters starting at the beginning of the line, and ending at the current cursor position.

For example, if you have these commands in your history file (in the following order):

ls -al /opt
ls -al /home
ls -al /home/x

And if you type this in the terminal and keep pressing the up arrow:

ls -al

You'll first get /home/x, then /home, then /opt.

If you type:

ls -al /h

You'll first get /home/x, then /home.

By pressing the down arrow, you would go in the opposite direction.

Note: ~/.inputrc is a configuration file for GNU Readline, so this will not only enable this feature for Bash, but also for everything else that uses GNU Readline.

Variations

If you prefer PgUp/PgDown instead of up/down arrow keys, you can use something like this:

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

Or Ctrl+p/Ctrl+n:

"\C-p":history-search-backward
"\C-n":history-search-forward

Global scope

If you'd like to enable this behavior for all users on the system, you can use global /etc/inputrc instead of the local ~/.inputrc file. The syntax is the same.


Ask me anything / Suggestions

If you have any suggestions or questions (related to this or any other topic), feel free to contact me. ℹī¸


If you find this site useful in any way, please consider supporting it.