Bash command to copy before cursor and paste after

bashclipboardcommand lineline-editor

I am not sure how to word this, but I often I find myself typing commands like this:

cp /etc/prog/dir1/myconfig.yml /etc/prog/dir1/myconfig.yml.bak

I usually just type out the path twice (with tab completion) or I'll copy and paste the path with the cursor. Is there some bashfoo that makes this easier to type?

Best Answer

There are a number of tricks (there's a duplicate to be found I think), but for this I tend to do

cp /etc/prog/dir1/myconfig.yml{,.bak}

which gets expanded to your command.

This is known as brace expansion. In the form used here, the {} expression specifies a number of strings separated by commas. These "expand" the whole /etc/prog/dir1/myconfig.yml{,.bak} expression, replacing the {} part with each string in turn: the empty string, giving /etc/prog/dir1/myconfig.yml, and then .bak, giving /etc/prog/dir1/myconfig.yml.bak. The result is

cp /etc/prog/dir1/myconfig.yml /etc/prog/dir1/myconfig.yml.bak

These expressions can be nested:

echo a{b,c,d{e,f,g}}

produces

ab ac ade adf adg

There's a variant using numbers to produce sequences:

echo {1..10}

produces

1 2 3 4 5 6 7 8 9 10

and you can also specify the step:

echo {0..10..5}

produces

0 5 10
Related Question