How can Bash execute a command in a different directory context?
I have a common command that gets called from within very specific directories. There is only one executable sitting in /bin for this program, and the current working directory is very important for running it correctly. The script affects the files that live inside the directory it is run within.
Now, I also have a custom shell script that does some things in one directory, but I need to call that command mentioned above as if it was in another directory.
How do you do this in a shell script?
Solution 1:
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.
Solution 2:
(cd /path/to/your/special/place;/bin/your-special-command ARGS)
Solution 3:
You can use the cd
builtin, or the pushd
and popd
builtins for this purpose. For example:
# do something with /etc as the working directory
cd /etc
:
# do something with /tmp as the working directory
cd /tmp
:
You use the builtins just like any other command, and can change directory context as many times as you like in a script.
Solution 4:
If you want to return to your current working directory:
current_dir=$PWD;cd /path/to/your/command/dir;special command ARGS;cd $current_dir;
- We are setting a variable
current_dir
equal to yourpwd
- after that we are going to
cd
to where you need to run your command - then we are running the command
- then we are going to
cd
back to our variablecurrent_dir
Another Solution by @apieceofbart
pushd && YOUR COMMAND && popd