Temporarily change current working directory in bash to run a command

BashShellTerminalWorking Directory

Bash Problem Overview


I know I can use cd command to change my working directory in bash.

But if I do this command:

cd SOME_PATH && run_some_command

Then the working directory will be changed permanently. Is there some way to change the working directory just temporarily like this?

PWD=SOME_PATH run_some_command

Bash Solutions


Solution 1 - Bash

You can run the cd and the executable in a subshell by enclosing the command line in a pair of parentheses:

(cd SOME_PATH && exec_some_command)

Demo:

$ pwd
/home/abhijit
$ (cd /tmp && pwd)  # directory changed in the subshell
/tmp 
$ pwd               # parent shell's pwd is still the same
/home/abhijit

Solution 2 - Bash

bash has a builtin

pushd SOME_PATH
run_stuff
...
...
popd 

Solution 3 - Bash

Something like this should work:

sh -c 'cd /tmp && exec pwd'

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
QuestionEthan ZhangView Question on Stackoverflow
Solution 1 - BashcodaddictView Answer on Stackoverflow
Solution 2 - BashpizzaView Answer on Stackoverflow
Solution 3 - BashyazuView Answer on Stackoverflow