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.
Note: this is a wiki article from BetterWays.dev Linux/Unix series, you can find the latest (better formatted) version here: https://betterways.dev/linux-zsh-style-up-down-arrows-in-bash-readline
If you find this type of post interesting, please let me know (with reactions and/or comments).
Top comments (1)
Or just type ctrl-r to search backwards if you prefer default cursor key behaviour