8

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.

1
  • If you are familiar with vi, why not switching (and staying) in vi mode?
    – jlliagre
    Jan 7, 2016 at 22:31

2 Answers 2

13

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

2
  • 2
    As I like having my readline configuration reside completely within ~/.inputrc , you can drop the bind and surrounding single quotes and add it directly to ~/.inputrc
    – Roshan
    Nov 6, 2013 at 12:17
  • In case it helps anyone else you can get this working in fish shell by adding bind \cb backward-bigword and bind \cf forward-bigword to your ~\.config\config.fish
    – timbram
    Dec 21, 2017 at 17:55
7

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.

1
  • 1
    Good stuff! Note that this feature was introduced in bash 4.0 so it's not working on the stock Mac OS Bash version.
    – sitaktif
    Mar 2, 2017 at 13:19

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .