Duplicate the last argument of the current command

From raju

Task

The idea here is to duplicate the last argument of the current command in bash.

manual method

place the cursor at the end, type Ctrl-w to erase the last word, then type Ctrl-y twice to yank it.

Ex:-

    $ mv oldname _    # _ is your cursor
    

After typing Ctrl-w

    $ mv _
    

After typing Ctrl-y twice

    $ mv oldname oldname _
    

Now the second argument can be edited in place if needed.

This solution works on anything that uses GNU readline.

automation

To automate it, add this line to ~/.inputrc

    # Use Ctrl-t to copy the word before the cursor
    \C-T: " \C-W\C-Y\C-Y\b"
    

Reload with

    $ bind -f ~/.inputrc
    

Now Ctrl-t does it:

    $ mv oldname_
    

Hit Ctrl-t

    $ mv oldname oldname_
    

Ref:-

tags | copy the word before the cursor

words with spaces

The Ctrl-t shortcut will not work if the last argument has spaces in it. For example if we have

    $ mv "old name"_
    

Hit Ctrl-t

    $ mv "old name" name"_
    

In this case, use the manual method. Type as many Ctrl-w s as needed to gobble up the whole thing. Then regurgitate the entire thing twice with Ctrl-y Ctrl-y. All the consecutive Ctrl-w operations just add to the clipboard.

For example

    $ mv "old name"_
    

Hit Space Ctrl-w Ctrl-w Ctrl-y Ctrl-y Backspace

    $ mv "old name" "old name"_
    

Another example

    $ mv "first middle last"_
    

Hit Space Ctrl-w Ctrl-w Ctrl-w Ctrl-y Ctrl-y Backspace

    $ mv "first middle last" "first middle last"