A couple of Readline incantations

You may have never heard of GNU Readline before, but provably you have used it many times. Readline is a library for command-line interfaces that manages user interaction: it’s the thing that shows you a prompt and allows you to write commands in programs like Bash and the Postgres client.

One of the “tricks” you learn when using a shell for the first time is to press Tab to autocomplete commands and paths, that’s Readline. You also learn that you can press Up (or Ctrl+p) to navigate the command history, that’s Readline too. There are of course many key bindings to edit text in different ways, and if you are a daily CLI user reading the Readline manpages is a must. One that I use all the time with Bash, for example, is Alt+. (aka yank-last-arg) which grabs the last argument of the previous command, so if you just created a new directory like mkdir mynewproject you can quickly go inside it by typing cd followed by Alt+.1 and enter. It is also possible to indicate which argument in particular you want from the history by using Alt+arg_number followed by Ctrl+Alt+Y (aka yank-nth-arg).

A very cool thing about Readline is that it allows us to create new custom key bindings. For instance, ages ago I wrote the following logical extension of the yank-nth-arg that yanks all the arguments starting from the nth argument:

# /etc/inputrc
"\e,": "0\eb!:\ef\C-b\C-d*\e\C-e"

To use this, you first have to type the initial argument number followed by Alt+, (i.e. a comma instead of period). This basically combines already existing features into one Readline command, but the power of Readline doesn’t stop there: You can also create completely new functionalities by running shell commands and using their output on the fly!

This is one I personally think is a must for Bash:

"\e\C-p": "$(printf %q "$(pwd)")\e\C-e"

Now you can press Ctrl+Alt+P to get the current full path, which you can use, for example, to quickly cd into any directory ancestor by pressing Alt and then Backspace as many times as you need.