How can Bash execute a command in a different directory context? How can Bash execute a command in a different directory context? shell shell

How can Bash execute a command in a different directory context?


Use cd in a subshell; the shorthand way to use this kind of subshell is parentheses.

(cd wherever; mycommand ...)

That said, if your command has an environment that it requires, it should really ensure that environment itself instead of putting the onus on anything that might want to use it (unless it's an internal command used in very specific circumstances in the context of a well defined larger system, such that any caller already needs to ensure the environment it requires). Usually this would be some kind of shell script wrapper.


(cd /path/to/your/special/place;/bin/your-special-command ARGS)


You can use the cd builtin, or the pushd and popd builtins for this purpose. For example:

# do something with /etc as the working directorycd /etc:# do something with /tmp as the working directorycd /tmp:

You use the builtins just like any other command, and can change directory context as many times as you like in a script.