使用 Bash CTRL 在单词/字符串之间移动光标

我习惯于使用 CTRL键在使用左右箭头键时移动得更快(到一个单词的末尾,而不是一次一个字符)。

我能在 Bash 里这么做吗?

我也许可以编写代码,但我想知道是否有更容易/已经完成的东西。

29471 次浏览

With the default readline key bindings, ALT+B goes back one word, ALT+F goes forward one word.

The default Ubuntu setup additionally provides CTRL+arrows like you're used to. These are in /etc/inputrc and specified as follows:

# mappings for Ctrl-left-arrow and Ctrl-right-arrow for word moving
"\e[1;5C": forward-word
"\e[1;5D": backward-word
"\e[5C": forward-word
"\e[5D": backward-word
"\e\e[C": forward-word
"\e\e[D": backward-word

Not sure why we need three of them...

As Thomas explained, you can add the bindings to /etc/inputrc.

Another alternative so it loads every time you log in, is putting them in ~/.bashrc like this:

#use ctl keys to move forward and back in words
bind '"\eOC":forward-word'
bind '"\eOD":backward-word'

I learned that you can use cat > /dev/null to look at the characters that your keyboard is sending, e.g., CTRL + right arrow shows:

^[OC

where ^[ is the same as \e so that's where the code comes from in the bind command.

You can also look up bindings like this:

bind -p | grep forward-word

All of this is pretty damn awesome and I'm glad I found out some more power of bash.

A .inputrc in your home directory will cause ctrl+left to stop working on Ubuntu (for example).

To get everything working, add the following to ~/.inputrc:

# Include system-wide inputrc, which is ignored by default when
# a user has their own .inputrc file.
$include /etc/inputrc

credit to f.kowal

Add $include /etc/inputrc

in ~/.inputrc

Worked for CentOS Linux release 8.2.2004 (Core)