The Computer Oracle

How do I perform commands in another folder, without repeating the folder path?

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Book End

--

Chapters
00:00 How Do I Perform Commands In Another Folder, Without Repeating The Folder Path?
00:32 Answer 1 Score 74
00:47 Accepted Answer Score 123
01:34 Answer 3 Score 21
01:53 Answer 4 Score 11
02:04 Thank you

--

Full question
https://superuser.com/questions/596712/h...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#linux #commandline #bash #shell #script

#avk47



ACCEPTED ANSWER

Score 123


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.




ANSWER 2

Score 74


Run the operation in a subshell.

( cd /folder1/folder2/folder3 && mv file.txt file-2013.txt )

The change of working directory won't be propagated to the parent shell.




ANSWER 3

Score 21


If you want clever, here's bash history expansion

mv /folder1/folder2/folder3/file.txt !#:1:h/file-2013.txt

I wouldn't use this myself since I find it impossible to memorize. I do occassionally use the vim equivalent, but have to look it up almost every time.




ANSWER 4

Score 11


You can set a variable. Of course this has the side-effect of leaving the variables around.

D=/folder1/folder2/folder3; mv $D/file.txt $D/file-2013.txt