[Nottingham] Bash Variables

Duncan Fyfe djf at star.le.ac.uk
Fri Aug 1 15:55:37 BST 2008


On Fri, 2008-08-01 at 14:24 +0100, Mike Haber wrote:
> Hi All,
> Just had a query from a colleague that I can't answer and is
> interesting.
> 
> When using bash and exporting variables, is there a way of listing the
> previous values that a variable contained?
> 
> For example if a script is run that contains 'export foo=bar' can the
> previous values for $foo be accessed after the script has run?
> 

It depends what you mean by "run".
I have attached a script below which demonstrates the difference.

With newshell=Y a new shell is created for each script run.  Each
child-script inherits the environment from its parent shell and while
the child is able to modify its environment (export X=Y) these changes
do not propagate back the parent environment and the parent will still
have access to the "previous value".  This is why 'cd' has to be a shell
built - it would not be able to modify PWD in your current shell if it
were a normal executable.

With newshell=N everything is executed in the same shell so there are no
previous values to retrieve - only what you changed it to with the most
recent export. 

HTH 

Have fun,
Duncan

#!/bin/bash
# Usage: ./test1.sh Y|N

# Run children in new shells or not.
newshell=$1
[ "X$newshell" != "XY" -a "X$newshell" != "XN" ] && newshell=Y

v=$2
[ "X$v" == "X" ] && v=1

# change an environment variable
export FOO=$v
echo Pre: v=$v , FOO=$FOO
if [ $FOO -lt 5 ]; then
	let w=v+1
	if [ "$newshell" == "Y" ]; then 
		./test1.sh $newshell $w
	elif [ "$newshell" == "N" ]; then
		. test1.sh $newshell $w
	fi
else
	echo "Finished"
fi
echo Post: v=$v , FOO=$FOO
### END OF SCRIPT

# Giving:
./test1.sh Y
Pre: v=1 , FOO=1
Pre: v=2 , FOO=2
Pre: v=3 , FOO=3
Pre: v=4 , FOO=4
Pre: v=5 , FOO=5
Finished
Post: v=5 , FOO=5
Post: v=4 , FOO=4
Post: v=3 , FOO=3
Post: v=2 , FOO=2
Post: v=1 , FOO=1

./test1.sh N
Pre: v=1 , FOO=1
Pre: v=2 , FOO=2
Pre: v=3 , FOO=3
Pre: v=4 , FOO=4
Pre: v=5 , FOO=5
Finished
Post: v=5 , FOO=5
Post: v=5 , FOO=5
Post: v=5 , FOO=5
Post: v=5 , FOO=5
Post: v=5 , FOO=5





More information about the Nottingham mailing list