Bash and Zsh – How to Delete a Word Backward at the Command Line

bashkeyboard shortcuts

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?

Best Answer

Ctrl+W is the standard "kill word" (aka werase). Ctrl+U kills the whole line (kill).

You can change them with stty.

-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.

Related Question