Binding backward-kill-word to Ctrl+w

readline does not bind over Ctrl-W since it is handled by the terminal driver by default:

$ stty -a
(...) werase = ^W; (...)

To disable this, you have to run (in ~/.bashrc):

stty werase undef
bind '"\C-w": backward-kill-word'

.inputrc will not help here since it is read when Ctrl-W is still assigned to werase.

Also note that \C-w format keyseqs must be enclosed in double-quotes, as above.


Different terminals may handle Alt-Backspace differently.

  • PuTTY and GNOME Terminal (with default settings) send 1b 7f (ESC DEL)
  • Xterm with metaSendsEscape: true sends 1b 08 (ESC BS).
  • Xterm without metaSendsEscape sends 88 (HTS, or BS with highest bit set).

Xterm has a few settings to control the behavior of Alt key (called Meta in Xterm and X11 in general). With metaSendsEscape, holding Alt will prefix the keypress with an ESC (hex 1b). Without the setting (default mode), Alt will set the highest bit of the input character, resulting in special characters. (For example, Alt-N results in ESC n and î respectively.)

As far as I can remember, Terminal.app also has a similar setting to control the behavior of Meta/Alt/whatever-Macs-use.


grawity wrote that this cannot be controlled in the .inputrc file, but that is incorrect.

If you set bind-tty-special-chars off in your .inputrc, you can then customize the behavior of the special terminal chars.

For example:

set bind-tty-special-chars off
Control-u: kill-whole-line
Control-w: backward-kill-word

For the record, the answer as it applies to iTerm2 is to set Alt-Backspace (or Opt ⌥- on Mac) to send Hex Codes 0xb1 and 0x7f in order to perform the backward-kill-word action which treats non-alphanumeric characters as delimiters.

For distinction, here's the behavior I'm describing, in which pressing Opt ⌥- one time changes this:

echo "/example/filepath/with_non-alpha.characters@blah:meh

to this:

echo "/example/filepath/with_non-alpha.characters@blah:

And subsequent presses of Opt ⌥-:

echo "/example/filepath/with_non-alpha.characters@

echo "/example/filepath/with_non-alpha.

echo "/example/filepath/with_non-

echo "/example/filepath/with_

echo "/example/filepath/

Here's what the setting looks like in iTerm2: enter image description here

So, specific to Putty and Terminal, grawity's answer is great. But having spent an embarrassing amount of time looking for how to apply the setting in iTerm2, this superuser post seems to come up most frequently, so it seemed responsible to provide the relevant info as it applies to iTerm2 as an Answer attached to this Question.

Tags:

Bash

Readline