When a shell script is executed ...

When a shell script is executed, a child shell [process] is spawned. If commands are executed in child shell and there is output to stdio/stderr, it will be displayed in parent shell. However, setting of any environment variables in child shell is gone after child shell exits. It is not seen in parent shell.

A small program that I learnt in my Linux Systems Programming course is reproduced here for understanding. 

supadhy@linux# cat echo.sh 
#!/bin/tcsh
ps -f
echo "Executing $0"

#set a new variable in the child shell 
setenv EXPL exampleshell 
echo $EXPL

Output of this program:

supadhy@linux# ./echo.sh 
UID        PID  PPID  C STIME TTY          TIME CMD
supadhy  20463 24124  0 16:51 pts/20   00:00:00 /bin/bash ./echo.sh
supadhy  20464 20463  0 16:51 pts/20   00:00:00 ps -f
supadhy  24124 24123  0 Mar08 pts/20   00:00:00 -/bin/tcsh
Executing ./echo.sh
exampleshell

Note that output of "ps -f" shows ./echo.sh shell script with PID=20463 and its PPID=24124, which is the shell from echo.sh file was executed. And obviously, PPID of "ps -f" is PID of echo.sh shell.

Now, after the shell script is done running, if we search for EXPL variable in parent shell, we'll not find it. 
supadhy@linux# echo $EXPL
EXPL: Undefined variable.


Parent shell will not have user defined variables if they are defined in child shell. If environment variables are modified by child, it will not be reflected in parent shell. It needs to be explicitly exported.

How to retain new variables across shells?
                         (to be continued ....)

Labels: , , ,