Is there a way to execute a command in a different directory without having to
cd to it? I know that I could simply
cd in and
cd out, but I'm just interested in the possibilities of forgoing the extra steps :)
I don't know if this counts, but you can make a subshell:
The directory is only changed for that subshell, so you avoid the work of needing to
Some programs have options with which you can tell them to chdir(2) themselves (e.g. GNU tar’s
Outside of such programs though, something will have to chdir. You could write and use some sort of compiled “binary” program instead of having the shell do it, but it probably would not yield much benefit.
In a comment in another answer, you gave an example:
If you are just interesting in avoiding having to “cd back”, then you can use a subshell to isolate the effect of the cd from your working shell instance.
You can package this up in a shell function.
(I dropped the
Not to undermine the value of answers given by other people, but I believe what you want is this:
Note the parens to invoke
Sadly, your example:
doesn't need a change to the dir, because
would do the same. Can't you get closer to your real problem? Because we might know a better solution for that too.
A complicated way to solve your problem, which is far away from the elegance of Michaels solution, is the usage of find, which has a switch '-execdir' to be performed in the dir, where a file is found. Badly adopted to your example:
Maybe it is useful for your real problem. -okdir instead of -execdir will ask you to confirm every invocation.
-okdir and -execdir might need gnu-find to be installed, which is typically used on Linux.
Here is something that should let you
(EDIT: slightly shorter version, thanks to @Random832)