lifetime and validiy of exported variables in bash script
I have created a bash script to run some other programs with customized environment variables. Here is my first script named
#!/bin/bash export PATH=$PATH":/home/user/cool/path" hello.sh exit 0
/home/user/cool/path I have the
#!/bin/bash echo Hello from $(pwd)
Running the frist script (run-hello.sh) yields:
Hello from /home/user
exportcalled in the first script is only valid for the duration that script was active ony? If after running the script I do
echo $PATHI will not see the added path by script…
Is this the intended behaviour? How can I make it presistence at least for the duration of the terminal?
Why does the result print
At first, you need to consider that when, under a shell you launch some shell script, your shell will fork a new shell (let’s call it sub-shell) that will execute the commands of the script.
Then man bash tells:
When a program is invoked it is given an array of strings called the environment. This is a list of name-value pairs, of the
The shell provides several ways to manipulate the environment. On invocation, the shell scans its own environment and
creates a parameter for each name found, automatically marking it for export to child processes. Executed commands inherit the environment. The
commands allow parameters and functions to be added to and deleted from the environment. If the value of a parameter in the
environment is modified, the new value becomes part of the environment, replacing the old. The environment inherited by any executed command
consists of the shell’s
initial environment, whose values may be modified in the shell, less any pairs removed by the
unsetcommand, plus any additions
Consequently, when you first export your
PATH, its new value becomes part of your sub-shell environment and is made available to any child process it will fire. (hello.sh for instance)
Therefore, if you run
echo $PATH right immediately after running hello.sh, the updated value should be displayed.
However, you exit your shell! (the sub-shell executing run-hello.sh terminates) Some ancestor of it (most likely the shell under which you had launched run-hello.sh) takes control back but in a complete unawareness of run-hello.sh environmental fiddlings.
So, yes, that is indeed the intended behaviour.
Now the present working directory of a task when launched is inherited from its parent. It will not be automagically changed to the directory the program resides in.
So I must suspect that your call to
run-hello.sh was made from the
To sum up with: The lifetime of whatever exported variable is equal to the lifetime of the task which is responsible for the export and the validity is guaranteed for the task itself and all of its children (at their launch time).