How to run 'cd' in shell script and stay there after script finishes?

You need to source the file as:

. myfile.sh

or

source myfile.sh

Without sourcing the changes will happen in the sub-shell and not in the parent shell which is invoking the script. But when you source a file the lines in the file are executed as if they were typed at the command line.


The script is run in a separate subshell. That subshell changes directory, not the shell you run it in. A possible solution is to source the script instead of running it:

# Bash
source yourscript.sh
# or POSIX sh
. yourscript.sh

While sourcing the script you want to run is one solution, you should be aware that this script then can directly modify the environment of your current shell. Also it is not possible to pass arguments anymore.

Another way to do, is to implement your script as a function in bash.

function cdbm() {
    cd whereever_you_want_to_go
     echo arguments to the functions were $1, $2, ...
}

This technique is used by autojump: http://github.com/joelthelion/autojump/wiki to provide you with learning shell directory bookmarks.


It can be achieved by sourcing. Sourcing is basically execute the script in the same shell whereas normal execution(sh test.sh or ./test.sh) will create sub shell and execute script there.

test.sh

cd development/
ls
# Do whatever you want.

Execute test.sh by

source test.sh

. is shortest notation for source. So you can also do by

. test.sh

This will execute the script and change the directory of current shell to development/.