How to change previous/next word shortcut in bash?

How do I configure Ctrl-Left and Ctrl-Right as previous/next word shortcuts for bash (currently alt-b and alt-f)?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

The correct answer depends on which terminal you are using.

For Gnome Terminal or recent versions of xterm, put this in ~/.inputrc:

"e[1;5C": forward-word
"e[1;5D": backward-word

For PuTTY, put this in your ~/.inputrc:

"eOC": forward-word
"eOD": backward-word

For rxvt, put this in your ~/.inputrc:

"eOc": forward-word
"eOd": backward-word

You can probably get away with putting all of those together in ~/.inputrc.

In all cases, you also need to put this in your ~/.bashrc (or ~/.zshrc):

export INPUTRC=~/.inputrc

If that doesn’t work, or you have a different terminal, go to your terminal and type Ctrl+V Ctrl+->. Then use that instead of "e[1;5C" or "eOC" above. Repeat for Ctrl+<-.

Note that you need to write the keyboard escape sequences using the inputrc syntax, e.g.

  • C means control
  • e means escape (which appears as ^[ when typing it using Ctrl+V above)

Method 2

If you’re using ZSH, you need to take a different method, because, quoting the relevant parts from ArchLinux’s ZSH guide:

Zsh does not use readline #like bash#, instead it uses its own and more powerful zle.

It does not read /etc/inputrc or ~/.inputrc.

After reading that guide, I figured I need a modren source of ZSH to get the general idea of how to do this from, and so I found this oh-my-zsh file which describes the behaviour I wanted,
I copied the relevant parts I wanted into my ~/.zshrc:

bindkey -e #Use emacs mode, it's more sane for beginners
bindkey '^[[1;5C' forward-word # [Ctrl-RightArrow] - move forward one word
bindkey '^[[1;5D' backward-word # [Ctrl-LeftArrow] - move backward one word
# Also, If you want to copy paste this into your zshrc,
# I'm pretty sure you would have to add this at the top : 
# setopt interactive_comments


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x