Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

This question already has an answer here:

What I want to do is basically

cp long/directory/path/file long/directory/path/file-copy

This or similar operations are pretty common. Typing out the whole path twice is obviously awkward, even with auto-completion or copy-paste. There are a couple of simple ways to do it, but none seems ideal:

  • First cd into the directory, then simply cp file file-copy. Least keystrokes, but I end up in the directory, which I didn't really want.
  • Wrap the above in a subshell, sh -c 'cd dir-path; cp file file-copy', to make the cp local. Fair enough, but that means I have to type the commands in a string literal, which disables auto-completion and isn't overall nice.
  • Define the dir as a variable, then just cp "$dir/file" "$dir/file-copy". Can work nicely, but I'm kind of paranoid about namespace pollution...
  • echo dir-path | while read p; do cd "$p"; cp file file-copy; done. Basically combines subshell-wrapping with variable definition, by emulating a lambda-calculus stype let-binding with read. I quite like it, but it's just a bit weird, and involves a lot of extra characters.
  • Anything I can come up with that uses sed 's/file/file-copy/' needs even more boilerplate around it.
  • Open the file with an editor, then save-as. Not well applicable to non-text files, and often resource-costly.

Is there a more elegant alternative? Ideally one that works with mv as well, analogously.

share|improve this question

marked as duplicate by Bernhard, jasonwryan, Gilles, slm, Patrick Dec 15 '13 at 1:04

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

add comment

1 Answer

up vote 2 down vote accepted

As per this question, you can use:

cp /long/path/to/file{,-copy}

This a shell expansion done by bash (not sure about others), so it will work with any command.

share|improve this answer
1  
When you find a question that duplicates another question, please flag it as a duplicate instead of answering it. Use the “flag” button on the question, select “it is a duplicate”, and enter the link to the question. –  Gilles Dec 14 '13 at 22:54
add comment

Not the answer you're looking for? Browse other questions tagged or ask your own question.