Linux/Unix: Quickly deleting the last word on the command line

📄 OneThingWell.dev wiki page | 🕑 Last updated: Oct 22, 2022

There are very handy shortcuts (that many people are not aware of), that you can use to quickly delete the last word/argument on the command line.

CTRL+w is the most known variant. For example, typing:

vim mydir/myfile^W

Will result in:

vim

This functionality is a part of GNU Readline and it works out of the box in Bash (and everything else that uses GNU Readline).

Readline function which does this is called unix-word-rubout. You can check that by doing something like bind -p | grep "\C-w":

"\C-w": unix-word-rubout

Alt+Backspace

But what if you don't want to use the white space as the separator, but any non-alphanumeric character?

There is a Readline command called backward-kill-word (bound to Alt+Backspace by default) which does exactly that:

vim mydir/myfile^[^?

Result:

vim mydir/

If you try to do bind -p | grep backward-kill-word, you should see something like this:

"\e\C-?": backward-kill-word

Remapping CTRL+w

CTRL+w is a bit more reachable than Alt+Backspace, so if you prefer to use it for the backward-kill-word functionality, you can do something like this:

bind '\C-w:backward-kill-word'

If you want to make the change permanent, add this to your ~/.bashrc.

ZSH

ZSH doesn't use Readline, but it provides CTRL+w functionality out of the box, although the provided functionality is closer to backward-kill-word (Alt+Backspace) in GNU Readline.


Comments and suggestions

You can use this form to submit a suggestion or a comment.

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