Create ~/.inputrc and add these lines:
# Respect default shortcuts.
$include /etc/inputrc
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.
Close and re-open your terminals for the new behaviour to become effective.
Read at the bottom for an explanation of $include /etc/inputrc or what to do if you already have the file ~/.inputrc.
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:
- Start
cat in a terminal (just cat, no further arguments).
- Type keys on keyboard, you will get things like
^[[A for up arrow and ^[[B for down arrow.
- Replace
^[ with \e.
For more information about ^[ and \e see here: https://unix.stackexchange.com/a/89817/380515
About the line $include /etc/inputrc:
Readline tries to read ~/.inputrc for configuration. If that file does not exists it will try to read /etc/inputrc. That means if ~/.inputrc exists it will not read /etc/inputrc.
Some distros have prepared some config in /etc/inputrc. If you then create ~/.inputrc you will lose the prepared config. This may or may not be what you want. To still keep the prepared config in /etc/inputrc you can use the line $include /etc/inputrc in your ~/.inputrc.
If you already have the file ~/.inputrc that means you either already know what you are doing. Or you inherited if from the person who set up your system. Or you previously followed a different guide which told you to create the file and forgot about it. Either way you might want to check /etc/inputrc and decide if you want to keep it with the line $include /etc/inputrc.