259

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
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
Ethan Zhang
  • 4,189
  • 3
  • 22
  • 17
  • 2
    why not keep it simple **cd SOME_PATH && run_some_command && cd -** the last command will take you back to the last pwd directory. – Sahil Jan 02 '15 at 03:21
  • @Sahil then it can't be run in parallel – Eyal May 19 '18 at 22:42

3 Answers3

461

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
Eric O. Lebigot
  • 91,433
  • 48
  • 218
  • 260
codaddict
  • 445,704
  • 82
  • 492
  • 529
  • That sort of invalidates the point of using `exec`, don't you think? – tripleee Apr 30 '12 at 10:32
  • @tripleee: I guess OP meant to execute any executable and not the exec. – codaddict Apr 30 '12 at 10:34
  • 1
    not working in shell file – Allan Ruin Sep 14 '16 at 13:14
  • 2
    @BeC use `function` rather than `alias`. Better two years late than never. – jez Feb 07 '19 at 18:30
  • 1
    best answer. works with multiline wrappers as well and premature exits – mjs Feb 24 '20 at 22:58
  • I won't see the output of the command if it runs in a subshell. – Hexworks Oct 26 '21 at 09:37
  • worth 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) – Pierre Nov 30 '21 at 14:08
  • Works in a bash script for me. Also, you can use `(cd /tmp && echo $(pwd))` to test the output from a script. – scottlittle May 29 '23 at 16:16
184

bash has a builtin

pushd SOME_PATH
run_stuff
...
...
popd 
pizza
  • 7,296
  • 1
  • 25
  • 22
41

Something like this should work:

sh -c 'cd /tmp && exec pwd'
yazu
  • 4,462
  • 1
  • 20
  • 14