Shell timesaver: binding keys to commands

📄 Wiki page | 🕑 Last updated: Oct 8, 2022

This is one of my favorite shell timesavers - you can bind keyboard shortcuts to commonly used commands by doing something like this:

bind -x '"\C-l":"ls -al"'

Executing this command will bind the \C-l (CTRL+l) key sequence to the ls -al command.

Now you can simply press the CTRL+l instead of typing the whole command (you'll see just the output of the command):

$ cd test_dir
# press CTRL+l
total 32
drwxr-xr-x  5 n n 4096 Sep 26 16:54 .
drwxr-xr-x 28 n n 4096 Sep  7 00:21 ..
drwxr-xr-x  2 n n 4096 Sep 26 16:23 d1
drwxr-xr-x  2 n n 4096 Aug 18 15:16 d2
drwxr-xr-x  2 n n 4096 Aug 18 15:16 d3
-rw-r--r--  1 n n    2 Sep 26 15:55 f1
-rw-r--r--  1 n n    2 Sep 26 15:55 f2
-rw-r--r--  1 n n    2 Sep 26 15:55 f3

If you want to make the change permanent, you can put the bind command into your ~/.bashrc, and it will be automatically executed when you open a new shell.

Alternatives

Alternatively, if you want to insert the command into the current line, you can do something like this:

bind '"\C-l":"ls -l\n"

Now the command will be visible:

$ d cd test_dir/
# press CTRL+l
$ ls -l
total 24
drwxr-xr-x 2 n n 4096 Sep 26 16:23 d1
drwxr-xr-x 2 n n 4096 Aug 18 15:16 d2
drwxr-xr-x 2 n n 4096 Aug 18 15:16 d3
-rw-r--r-- 1 n n    2 Sep 26 15:55 f1
-rw-r--r-- 1 n n    2 Sep 26 15:55 f2
-rw-r--r-- 1 n n    2 Sep 26 15:55 f3

zsh

zsh doesn't have the built-in bind command, you can use bindkey:

bindkey -s '\C-l' "ls -al\n"

Alternatively, you can bind a function with something like this:

myfn() { ls -al; zle redisplay }
zle -N myfn
bindkey '\C-l' myfn

Ask me anything / Suggestions

If you have any suggestions or questions (related to this or any other topic), feel free to contact me. ℹī¸


If you find this site useful in any way, please consider supporting it.