Custom Key Bindings / Keyboard Shortcuts in Bash

Bash is so powerful that you can keep digging and finding out newer secrets all the time. We already use bash keyboard bindings – Ctrl d to exit the terminal, Ctrl r for reverse search and so on. Now won’t it be convenient if you could assign keyboard bindings to commands of your choice, to execute them quickly or just to insert lengthy commands which you use repeatedly with subtle changes. Lets look at an example.

grep --exclude-dir wp-content -rnH is_singular *

I use the above command to search my wordpress directory for different things, the above command is to search is_singular. I grep the wordpress directory quite frequently, but not often enough that it would be retained in my bash history so that I could do a Ctrl r and look for the previous instance easily. This is a scenario when a keyboard binding for the command would be so useful. And its so easy to set up.

bind '"\ew"':"\"grep --exclude-dir wp-content -rnH is_singular *\""

Using the bind command, I created a keyboard binding of \ew aka Alt w for the lengthy grep command. Now I can press Alt w whenever I want to search the wordpress directory, modify the inserted command and execute it. To make it permanent across sessions, add the command to the .bashrc in your home directory.

If you wish to execute the command instead of just inserting it, all you need to do is add \C-m at the end of the command. \C-m aka Ctrl m is nothing but the equivalent of the Enter key. Press the key combination in your terminal and you’ll see. The resulting command with \C-m included is:

bind '"\ew"':"\"grep --exclude-dir wp-content -rnH is_singular *\C-m\""

So how do I know \ew is the equivalent of Alt w. Well its very easy. The read command will echo the character codes thats you need to use.

@~$ read
^[w

Executeh the read command. The command waits for an input. Press Alt w and you will see the output you can see above. ^[ is the equivalent of Alt/Esc which is denoted by \e. Hence ^[w is equal to \ew. You can try various combinations like Alt Shift 5 etc.

The read method doesn’t work for Ctrl commands. HoweverCtrl based keyboard bindings are very straightforward as well. \C is equivalent to Ctrl. \C-m is equivalent to Ctrl m.

Thats it. I hope this is enough ammunition to go cracking at your custom keyboard bindings.

Leave a Reply