Change the current directory from a Bash script

artemb picture artemb · May 17, 2009 · Viewed 294.3k times · Source

Is it possible to change current directory from a script?

I want to create a utility for directory navigation in Bash. I have created a test script that looks like the following:

#!/bin/bash
cd /home/artemb

When I execute the script from the Bash shell the current directory doesn't change. Is it possible at all to change the current shell directory from a script?

Answer

Norbert Hartl picture Norbert Hartl · May 17, 2009

When you start your script, a new process is created that only inherits your environment. When it ends, it ends. Your current environment stays as it is.

Instead, you can start your script like this:

. myscript.sh

The . will evaluate the script in the current environment, so it might be altered