Temporarily change current working directory in bash to run a command
158,050
Solution 1
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 has a builtin
pushd SOME_PATH
run_stuff
...
...
popd
Solution 3
Something like this should work:
sh -c 'cd /tmp && exec pwd'
Related videos on Youtube
Author by
Ethan Zhang
I am the bone of my JavaScript Linux is my body, and Vim is my blood.
Updated on June 18, 2020Comments
-
Ethan Zhang about 4 years
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
-
Sahil over 9 yearswhy not keep it simple cd SOME_PATH && run_some_command && cd - the last command will take you back to the last pwd directory.
-
Eyal about 6 years@Sahil then it can't be run in parallel
-
-
tripleee about 12 yearsThat sort of invalidates the point of using
exec
, don't you think? -
codaddict about 12 years@tripleee: I guess OP meant to execute any executable and not the exec.
-
Fr0sT about 11 years+1, pushd/popd is ideal for this. Just don't forget to popd before you exit.
-
ron rothman almost 11 yearsNot necessarily a good solution if run_stuff can fail (and the script exits). You'd be stuck in SOME_PATH.
-
Allan Ruin almost 8 yearsnot working in shell file
-
galois over 6 years@ron.rothmanℝℝ couldn't you just do something like
pushd PATH; (run_stuff); [[ "$?" != 0 ]] && popd; ...; popd
-
jez over 5 years@BeC use
function
rather thanalias
. Better two years late than never. -
octoquad over 4 yearsIn my case, if the script execution failed e.g.
git pull
, I wanted to investigate in the directory withgit log
. -
Jason R Stevens CFA over 4 yearsWhat an excellent way to quickly update targets under another project while testing. Thanks!
-
mjs over 4 yearsbest answer. works with multiline wrappers as well and premature exits
-
Damian about 4 yearsbest answer for me!
-
Hexworks over 2 yearsI won't see the output of the command if it runs in a subshell.
-
Hexworks over 2 yearsThis should be the accepted answer! A subshell breaks the log output!
-
Pierre over 2 yearsworth noting: if your subshell to run the commands (in parentheses now) and that code does an "exit" (you want to stop execution), control goes back to the parent shell (the parent shell does NOT exit). This might be a difference if you refactor your code (execution doesn't stop anymore if something bad happens in the parentheses)