How can I delete a word backward at the command line (bash and zsh)?
How can I delete a word backward at the command line? I’m truly used to some editors deleting the last ‘word’ using Ctrl+Backspace, and I’d like that functionality at the command line too.
I am using Bash at the moment and although I could jump backward a word and then delete forward a word, I’d rather have this as a quick-key, or event as Ctrl+Backspace.
How can accomplish this?
Alt+Backspace works for me in bash and zsh.
You can also do this with CtrlW.
Another option is to set your own shortcut but this will depend on the terminal emulator you are using. For
rxvt and maybe others, add this line to your
~/.inputrc (create the file if it does not exist):
## rxvt, xterm "b":backward-kill-word
gnome-terminal and its ilk seem to have AltBackspace by default but apparently require you to patch
readline() in order to get CtrlBackspace.
Ctrl+W is the standard "kill word" (aka
Ctrl+U kills the whole line (
You can change them with
-bash-4.2$ stty -a speed 38400 baud; 24 rows; 80 columns; lflags: icanon isig iexten echo echoe -echok echoke -echonl echoctl -echoprt -altwerase -noflsh -tostop -flusho pendin -nokerninfo -extproc -xcase iflags: -istrip icrnl -inlcr -igncr -iuclc ixon -ixoff ixany imaxbel -ignbrk brkint -inpck -ignpar -parmrk oflags: opost onlcr -ocrnl -onocr -onlret -olcuc oxtabs -onoeot cflags: cread cs8 -parenb -parodd hupcl -clocal -cstopb -crtscts -mdmbuf cchars: discard = ^O; dsusp = ^Y; eof = ^D; eol = <undef>; eol2 = <undef>; erase = ^?; intr = ^C; kill = ^U; lnext = ^V; min = 1; quit = ^; reprint = ^R; start = ^Q; status = <undef>; stop = ^S; susp = ^Z; time = 0; werase = ^W; -bash-4.2$ stty werase ^p -bash-4.2$ stty kill ^a -bash-4.2$
Note that one does not have to put the actual control character on the line,
stty understands putting
^ and then the character you would hit with control.
After doing this, if I hit Ctrl+P it will erase a word from the line. And if I hit Ctrl+A, it will erase the whole line.
On Mac, you can use:
In Ubuntu 18.04.4 pressing Ctrl+V and then Ctrl+Backspace reveals that the Ctrl+Backspace combination is written as
You can show all current terminal key combinations using
stty -a. In this case we want to change
^H which can be done with
stty werase ^H
For any other key you want to remap you would again see how to write the new combination using Ctrl+V followed by the combination.
And you can find the command name (such as
werase) by looking at
stty -a and looking for the key combination an action is currently bound to.
Surprisingly, esc then delete works on macOS too.
Also, if using iTerm2, you can update the default profile:
Keys > Key Mapping > Presets > Natural Text Editing