Script to change current directory (cd, pwd)

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

For small tasks such as this, instead of creating script, create an alias like this,

$ alias cdproj='cd /dir/web/www/proj'

You should add this to your .bashrc file, if you want it set for every interactive shell.

Now you can run this as $ cdproj.


Use exec bash at the end

A bash script operates on its current environment or on that of its children, but never on its parent environment.

However, this question often gets asked because one wants to be left at the bash prompt in a certain directory after the execution of a bash script from another directory.

If this is the case, simply execute a child bash instance at the end of the script:

#!/usr/bin/env bash
cd desired/directory
exec bash

This creates a new subshell. Type Ctrl+D or exit to return to the first shell where the script was initially started.

Update

At least with newer versions of bash, the exec on the last line is no longer required. Furthermore, the script can be made to work with whatever preferred shell by using the $SHELL environment variable. This then gives:

#!/usr/bin/env bash
cd desired/directory
$SHELL