Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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: superuser.com/questions/176783/… –  lesmana May 1 '11 at 12:46

4 Answers 4

up vote 1 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

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.

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

. myscript.sh
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
1  

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

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 Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.