Linux – How to perform commands in another folder, without repeating the folder path

bashcommand linelinuxscriptshell

Is there a clever way to do copy and move operations or a command to duplicate a file, without having to do a cd, then mv after, at the same folder?

For example, I have to run the following:

mv /folder1/folder2/folder3/file.txt /folder1/folder2/folder3/file-2013.txt

Note that the directory to where I'm moving the file is the same, but I have to put the whole path again and sometimes it gets annoying. I'm curious to know if there's another way to do that without having to put the whole path again, because the operation would be done in the same path.

Best Answer

Simply use brace expansion:

mv /folder1/folder2/folder3/{file.txt,file-2013.txt}

This is equivalent to writing:

mv /folder1/folder2/folder3/file.txt /folder1/folder2/folder3/file-2013.txt

Brace expansion lets you supply more arguments, of course. You can even pass ranges to it, e.g. to create a couple of test folders, you can run mkdir test_{a..z}, and starting with Bash 4, you can create zero-padded sequences as well, as in touch foo{0001..3}, which creates foo0001, foo0002 and foo0003. The Bash Hackers Wiki has an article with a couple of examples for you.

If you have to use two different commands, use a subshell and cd there first, as in @Ignacio's answer.