In Bash can I copy the last typed argument to the cursor position?

You can use Ctrl+W to cut the argument and store it in your clipboard, and then Ctrl+Y to paste it again:

cp my_file_nameCtrl+W Ctrl+Y originals/Ctrl+Y

One way of doing it is using brace expansion:

cp {,originals/}my_file_name

Complicated usage, but simpler setup:

You can bind a keystroke (I'll use Ctrl-Q) to the readline copy-backward-word function and do this:

Alt-2 Ctrl-Q Ctrl-y Ctrl-Alt-h

That means:

  • digit-argument copy-backward-word (copy the two preceding words)
  • yank (paste)
  • backward-kill-word (get rid of the extra word)

To bind the keystroke at the command line:

bind '"\C-q": copy-backward-word'

or add this to your ~/.inputrc:

"\C-q": copy-backward-word

Simpler usage, but more complicated setup:

You can make that long keystroke sequence into a macro triggered by one keystroke (I'll use Alt-q here and make use of the Ctrl-q binding from above):

At a shell prompt:

bind '"\eq": "\e2\C-q\C-y\e\C-h"'

or in your ~/.inputrc:

"\eq": "\e2\C-q\C-y\e\C-h"

Remember, you'll also need to bind Ctrl-q as above.

Now to copy the word before the current one all you need to press is Alt-q.

Tags:

Bash