Home

Easy key bindings in Bash

Written on 2021-06-11 Last edited on 2021-06-12

Key bindings are a nice way of being even faster in the shell than by using aliases. However, some of the people who set them up do so via Readline using escape sequences, which can be quite messy:

my_function() {
    echo "I've just pressed Control + f!"
}

bind '"\C-f": "\C-e\C-u$(my_function)\e\C-e\er\C-m"'

There is however a simpler way of dealing with those when using Bash: it supports a -x flag which interprets the binding as a shell function rather than a Readline function or command:

my_function() {
    echo "I've just pressed Control + f!"
}

bind -x '"\C-f": "my_function"'

Note that bind -x doesn't add the command to the history, which can either be a good or bad thing depending on the use-case. If that is preferred, it can be manually appended with history -s command.