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

BashShellWorking Directory

Bash Problem Overview


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?

Bash Solutions


Solution 1 - Bash

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 - Bash

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

Solution 3 - Bash

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 - Bash

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;
  1. We are setting a variable current_dir equal to your pwd
  2. after that we are going to cd to where you need to run your command
  3. then we are running the command
  4. then we are going to cd back to our variable current_dir

Another Solution by @apieceofbart pushd && YOUR COMMAND && popd

Solution 5 - Bash

Just a tibit helpful info:

This will change the shell directory to ~/project

function mymake() {
	cd ~/project && make $1
}

This won't

function mymake() (
	cd ~/project && make $1
)

to run

mymake something

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMarty WallaceView Question on Stackoverflow
Solution 1 - BashgeekosaurView Answer on Stackoverflow
Solution 2 - BashbmarguliesView Answer on Stackoverflow
Solution 3 - BashTodd A. JacobsView Answer on Stackoverflow
Solution 4 - Bashabc123View Answer on Stackoverflow
Solution 5 - BashTimo HuovinenView Answer on Stackoverflow