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 ?
|
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 ? |
||||
|
|
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:
or:
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:
This, when called with |
|||||
|
|
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
|
|||||||
|
|
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:
Unlike whole scripts, functions are executed in the context of the current shell. |
|||
|
|
|
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. |
|||
|
|