On macOS, using bash. I want to map the Option+left arrow
keys to go back a word, and Option+right arrow
keys to go forward a word.
Am sure this is common knowledge, but I wasn’t sure what to do. Thanks to this StackOverflow post, I figured it out.
In the terminal, run cat
and then press Option+left arrow
. This appears as ^[^[[D
. The ^[
bit is your escape key basically. In bash you’d represent it as \e
. So ^[^[[D
translates to \e\e[D
in bash.
Ditto for Option+right arrow
which translates to \e\e[C
in bash.
Armed with these two pieces of info, you can use the builtin bind
command to map them to back and forward word movements.
1 2 |
bind '"\e\e[D": backward-word' bind '"\e\e[C": forward-word' |
Add these to .bash_profile
(or .bashrc
) and you are in business.
Extra info: By default the Esc+b
and Esc+f
keys are bound to these two. That can be seen by the bind -q
command.
1 2 3 4 5 |
$ bind -q backward-word backward-word can be invoked via "\eb". $ bind -q forward-word forward-word can be invoked via "\ef". |
To make this useful in iTerm2 on macOS, one can map the Option
key to the Esc+
key. This does not map the Option
key to the Esc
key, but the Esc+
action – which basically means Esc
plus whatever key you press. Treats it like a modifier basically.