Execute a specific command in a given directory without cd'ing to it?
I don't know if this counts, but you can make a subshell:
$ (cd /var/log && cp -- *.log ~/Desktop)
The directory is only changed for that subshell, so you avoid the work of needing to cd -
afterwards.
Some programs have options with which you can tell them to chdir(2) themselves (e.g. GNU tar’s -C
/--directory
).
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:
execindirectory -d /var/log "cp *.log ~/Desktop"
Since the *.log
pattern is expanded by the shell itself (not cp), something will have to chdir to the directory before having a shell evaluate your command.
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.
(cd /path/to/dir && some command)
You can package this up in a shell function.
(I dropped the -d
option from your example usage since there is little point to this command if the directory is actually optional.)
runindir() { (cd "$1" && shift && eval "$@"); }
runindir /var/log 'cp *.log ~/Desktop' # your example
runindir /var/log cp \*.log \~/Desktop # eval takes multiple args
runindir /var/log cp \*.log ~/Desktop # it is okay to expand tilde first
Not to undermine the value of answers given by other people, but I believe what you want is this:
(cd /path/to && ./executable [ARGS])
Note the parens to invoke cd
in a sub-shell.