147

I want to run a script to simply change the current working directory:

#!/bin/bash
cd web/www/project

But, after I run it, the current pwd remains unchanged! How can I do that?

Sony Santos
  • 1,573
  • 2
  • 10
  • 7

11 Answers11

178

It is an expected behavior. The script is run in a subshell, and cannot change the parent shell working directory. Its effects are lost when it finishes.

To change the current shell's directory permanently you should use the source command, also aliased simply as ., which runs a script in the current shell environment instead of a sub shell.

The following commands are identical:

. script

or

source script
enzotib
  • 51,661
  • I use this all the time, except that I copy the script into my /usr/sbin directory which is in my $PATH for less typing. I also always use fully-qualified directory names in the scripts so they can be run from anywhere. – SDsolar Jul 24 '17 at 15:15
  • What's the relation to "./script.sh" ? I assumed it's the same as "source script.sh", but results are different – gebbissimo Jan 16 '21 at 19:28
  • @gebbissimo . in a path just means "current working directory", similar to .. which means "parent directory". It's what you always get when you run ls -a for example. The similarity to the . command is just a bad coincidence I think. ./ is required to execute programs that are not in PATH. If it's just an argument, like to the . command, then it's (mostly) redundant (programs can see the difference, try e.g. find subdir vs find ./subdir - you get equivalent but differently spelled output in this example). – hawk Jul 18 '21 at 11:37