30 March 2009

Bash (command line) shortcuts

Until today, I only used the following shortcuts on the command line:

ctrl+a → go to beginning of line
ctrl+e → go to end of line
ctrl+k → delete to end of line

And even though I was very frustrated by the fact that I had to use
the mouse to select/copy/paste etc, it never really occured to me to
google for "bash command line shortcuts"...

To make it short: bash uses the readline library.

The user documentation for readline is at:

All the shortcuts that exist on your machine can be found by using the
'bind' command:
$ bind -P | more
You'll have more shortcuts with:
$ bind -p | more
If you want to know how to use 'bind' to add shortcuts, check its help
$ help bind

Select/cut/paste require to first bind a shortcut to "kill-region":
$ bind "\C-xx": kill-region
(ctrl+x followed by x)

Now we need to select the string (create a "region").

A region is automatically created between a "mark" and the cursor. So, we only need to put the mark at one end of the region and to move the cursor
to the other end.

To create a mark use: ctrl+@ or ctrl+space,
then move the cursor, then hit ctrl+xx to "kill" the

Pasting requires ctrl+y.

But, the ctrl-y (Yank/paste) command works only within
the application from where the string was "killed". The "kill-ring" is
not shared by other applications (even though they may accept
ctrl-y as a Yank command).

So, if you want to get a string from terminal and paste it outside
(like select a command and paste it into a mail for ex), here is
something that may not be the most efficient way to go, but it works:

echo string | pbcopy
echo "complex string" | pbcopy

For ex, to put the above line in the pastebpard, I'd do:
echo "echo \"complex string\" | pbcopy" | pbcopy