Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash CTRL to move cursor between words/strings

Tags:

bash

I am use to using the CTRL key to move faster when using the left and right arrow keys (goes to end of a word, instead of one char at a time).

Can I do that in bash somehow?

I could probably code it, but I was wondering if there is something easier / already done.

like image 835
Bryan Ruiz Avatar asked Feb 17 '11 12:02

Bryan Ruiz


People also ask

How do I move the cursor in bash?

Move Cursor on The Command LineCtrl+A or Home – moves the cursor to the start of a line. Ctrl+E or End – moves the cursor to the end of the line. Ctrl+B or Left Arrow – moves the cursor back one character at a time. Ctrl+F or Right Arrow – moves the cursor forward one character at a time.

How do I go back faster in terminal?

ctrl-b: moves the cursor backward one character at a time (same as the left arrow). alt-f: moves the cursor forward one word (same as pressing ctrl + right arrow). alt-b: moves the cursor backward one word (same as pressing ctrl + left arrow).

How do you move the cursor in Terminal Mac?

Option + Right Arrow Moves Cursor Right by a Word in Mac Terminal.


3 Answers

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...

like image 101
Thomas Avatar answered Oct 18 '22 22:10

Thomas


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.

like image 42
Bryan Ruiz Avatar answered Oct 19 '22 00:10

Bryan Ruiz


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

like image 5
Constantin De La Roche Avatar answered Oct 18 '22 23:10

Constantin De La Roche