Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

In my bash file I have asked to navigate to some subdir, unzip a file and stay there but when I type pwd I can see i'm always back to home dir. Why ?

Any way to get shell stick to subdir ?

share|improve this question
see also:… – lesmana May 1 '11 at 12:46
up vote 2 down vote accepted

When you run a script, it opens a new subshell for it, thus not changing the environment variables (including your working directory: $PWD) of the shell you are in. If you want the script to run in the same shell as you are, thus retaining the changes in environment variables it makes, source it instead of executing. Like this:

source my-script


. my-script

This will, however, leave behind every temporary variable that your script uses. If you want to avoid it, create a function within the script, and declare all temporary variables local. Like this:

function main()
    local var1=whatever
    cd /path/to


This, when called with source, will leave behind all variable changes, like the working directory, but won't leave temporary variables behind.

share|improve this answer
Thank you very much, i'm new to Linux :) – asksuperuser Apr 16 '10 at 22:35
+1 for pointing out the "variable residue" and detailing a solution for that. – DevSolar May 7 '10 at 11:04

Executing a script runs it in a separate process. Changes to the working directory, environment variables, etc. are lost when the script exits.

To execute the script in the current bash process you need to source the script

share|improve this answer
Then is there a way to let her know I want to stay where I was ? – asksuperuser Apr 11 '10 at 13:28

Yes, you can create a function to do this. First, create a script which does all the heavy work.

Then create a function in .bashrc like so:

xcd () {
    local archive="$1" dir="$2"

    your_script "$archive"
    cd "$dir"

Unlike whole scripts, functions are executed in the context of the current shell.

See the BASH FAQ for an explanation.

share|improve this answer

Your bash script inherits a copy of the invoking shell's environment (working dir, shell variables, etc.), which is discarded when the script exits. If you test any shell variables e.g., by typing "echo $foo", they'll have retained whatever value (or be non-existent) they had before you ran the script, just as pwd did.

share|improve this answer

You must log in to answer this question.