1

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 ?

1

4 Answers 4

2

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

or:

. 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
    do-something
    ...
}

main

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

1
  • +1 for pointing out the "variable residue" and detailing a solution for that.
    – DevSolar
    May 7, 2010 at 11:04
4

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

. myscript.sh
2
1

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.

0

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.

You must log in to answer this question.