bash/readline for "move forward by whitespace-delimited word?"

In bash/readline, if you want to navigate through a command, often you have things like:

cat /home/foo/bar.txt /home/bar/baz.txt

If my cursor is at the end of the line (^e), and I want to move back to the start of the second argument, how do I move to the (next/previous) whitespace?

Readline has built-in Meta-f (forward) and Meta-b (backwards), but these will stop at the slashes in the paths, not move all the way to the whitespace.

vim has W and B which will do this, but vim movement mode is not enabled in readline/bash by default.


You can use vim movement commands in readline/bash even while still in emacs movement mode. The relevant readline commands are vi-fWord and vi-bWord. You can bind them to keyboard shortcuts such as CTRL-f and CTRL-b with the following in your .bash_profile:

bind '"\C-f":vi-fWord'
bind '"\C-b":vi-bWord'

Note that the double quoting is significant.

You can confirm that the bindings are working by running bind -p


There are Readline commands that let you move and treat words like the shell treats them for splitting: shell-forward-word and shell-backward-word1.

If you want to bind them to Ctrl+Meta+f and Ctrl+Meta+b to avoid overwriting the existing bindings, you can use

bind '"\M-\C-f": shell-forward-word'
bind '"\M-\C-b": shell-backward-word'

on the command line, or add

"\M-\C-f": shell-forward-word
"\M-\C-b": shell-backward-word

to the relevant inputrc file (usually ~/.inputrc).

Depending on the setting of convert-meta, \M- has to be replaced with \e.


1 Introduced in Bash 4.0.