Where do I find a list of terminal key codes to remap shortcuts in bash?
For example:
"\e[1;5C"
"\e[Z"
"\e-1\C-i"
I only know bits and pieces, like \e
stands for escape and C-
for Ctrl, but what are these numbers (1
) and letters (Z
)? What are the ;
, [
and -
signs for?
Is there only trial and error, or is there a complete list of bash key codes and an explanation of their syntax?
Those are sequences of characters sent by your terminal when you press a given key. Nothing to do with bash or readline per se, but you'll want to know what sequence of characters a given key or key combination sends if you want to configure readline
to do something upon a given key press.
When you press the A key, generally terminals send the a
(0x61) character. If you press
or
, then generally send the ^I
character also known as TAB
or \t
(0x9). Most of the function and navigation keys generally send a sequence of characters that starts with the ^[
(control-[), also known as ESC
or \e
(0x1b, 033 octal), but the exact sequence varies from terminal to terminal.
The best way to find out what a key or key combination sends for your terminal, is run sed -n l
and to type it followed by Enter on the keyboard. Then you'll see something like:
$ sed -n l
^[[1;5A
\033[1;5A$
The first line is caused by the local terminal echo
done by the terminal device (it may not be reliable as terminal device settings would affect it).
The second line is output by sed
. The $
is not to be included, it's only to show you where the end of the line is.
Above that means that Ctrl-Up (which I've pressed) send the 6 characters ESC
, [
, 1
, ;
, 5
and A
(0x1b 0x5b 0x31 0x3b 0x35 0x41)
The terminfo
database records a number of sequences for a number of common keys for a number of terminals (based on $TERM
value).
For instance:
TERM=rxvt tput kdch1 | sed -n l
Would tell you what escape sequence is send by rxvt
upon pressing the Delete key.
You can look up what key corresponds to a given sequence with your current terminal with infocmp
(here assuming ncurses
infocmp):
$ infocmp -L1 | grep -F '=\E[Z'
back_tab=\E[Z,
key_btab=\E[Z,
Key combinations like Ctrl-Up don't have corresponding entries in the terminfo
database, so to find out what they send, either read the source or documentation for the corresponding terminal or try it out with the sed -n l
method described above.