Bash Scripting – Script to Change Current Directory

bashcd-commandenvironment-variablesscripting

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?

Best Answer

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