Ethan Zhang Ethan Zhang - 1 year ago 105
Bash Question

Temporarily change current working directory in bash to run a command

I know I can use

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

Answer Source

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)


$ pwd
$ (cd /tmp && pwd)  # directory changed in the subshell
$ pwd               # parent shell's pwd is still the same
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download