The Computer Oracle

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

Become or hire the top 3% of the developers on Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Magical Minnie Puzzles

--

Chapters
00:00 Question
00:43 Accepted answer (Score 123)
01:49 Answer 2 (Score 74)
02:08 Answer 3 (Score 21)
02:34 Answer 4 (Score 11)
02:51 Thank you

--

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

Accepted answer links:
[brace expansion]: http://www.gnu.org/software/bash/manual/...
[Bash Hackers Wiki]: http://wiki.bash-hackers.org/syntax/expa...
[as in @Ignacio's answer]: https://superuser.com/questions/596712/h...

Answer 3 links:
[history expansion]: http://www.gnu.org/software/bash/manual/...
[vim equivalent]: http://vimdoc.sourceforge.net/htmldoc/cm...

--

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