100 Useful Command-Line Utilities

by Oliver; 2014

52. bind

As discussed in detail in An Introduction to the Command-Line (on Unix-like systems) - Working Faster with Readline Functions and Key Bindings, ReadLine Functions (GNU Documentation) allow you to take all sorts of shortcuts in the terminal. You can see all the Readline Functions by entering:
$ bind -P  # show all Readline Functions and their key bindings
$ bind -l  # show all Readline Functions
Four of the most excellent Readline Functions are:
  • forward-word - jump cursor forward a word
  • backward-word - jump cursor backward a word
  • history-search-backward - scroll through your bash history backward
  • history-search-forward - scroll through your bash history forward
For the first two, you can use the default Emacs way:
  • Meta-f - jump forward one word
  • Meta-b - jump backward one word
However, reaching for the Esc key is a royal pain in the ass—you have to re-position your hands on the keyboard. This is where key-binding comes into play. Using the command bind, you can map a Readline Function to any key combination you like. Of course, you should be careful not to overwrite pre-existing key bindings that you want to use. I like to map the following keys to these Readline Functions:
  • Cntrl-forward-arrow - forward-word
  • Cntrl-backward-arrow - backward-word
  • up-arrow - history-search-backward
  • down-arrow - history-search-forward
In my .bash_profile (or, more accurately, in my global bash settings file) I use:
# make cursor jump over words
bind '"\e[5C": forward-word'    # control+arrow_right
bind '"\e[5D": backward-word'   # control+arrow_left

# make history searchable by entering the beginning of command
# and using up and down keys
bind '"\e[A": history-search-backward'  # arrow_up
bind '"\e[B": history-search-forward'   # arrow_down
(Although these may not work universally.) How does this cryptic symbology translate into these particular keybindings? Again, refer to An Introduction to the Command-Line (on Unix-like systems).

<PREV   NEXT>