Find and bind key sequences in bash

Learn how to use keyboard function keys within bash, or any other shell, by binding the key sequences to a particular shell command.

Delivered each Tuesday, TechRepublic's free Linux NetNote provides tips, articles, and other resources to help you hone your Linux skills. Automatically sign up today!

Most keyboards today come with an extra row of function keys at the top of the keyboard. These function keys can be customized and used within bash, or any other shell, by binding the key sequences to a command in the shell. Some keys may be intercepted by the window manager or the terminal program, such as konsole or gnome-terminal. You can retain those key bindings and use unassigned keys inside the shell, or you can reconfigure them to use a certain key in the shell instead.

To obtain the key sequence from a function key, use the read command. The following is an example of pressing the [F12] key:

$ read

Note that different keyboards will produce different key sequences, and modifiers to the function keys (such as [Ctrl][F12] or [Shift][F12]) will produce other sequences as well.

The next step is to bind that key sequence to a particular shell command. For example, you can bind [F12] to the "history-search-backward" shell command:

$ bind '"\e[24~": history-search-backward'

Make sure you write the key sequence as \e[24~ rather than ^[[24~. This is because the ^[ sequence is equivalent to the [Esc] key, which is represented by \e in the shell. So, for instance, if the key sequence was ^[[OP the resulting bind code to use would be \e[OP.

Not only does the bind command bind function keys, but you can also use bind to map key sequences (such as [Esc][P] or [Esc][Q]) by writing the bind key code as \ep and \eq respectively.

For a list of shell commands that you can use, examine the /etc/inputrc file.

About Vincent Danen

Vincent Danen works on the Red Hat Security Response Team and lives in Canada. He has been writing about and developing on Linux for over 10 years and is a veteran Mac user.

Editor's Picks