#sage_export []
#
#If is given, sets to and exports the variable.
#Furthermore, if this hasn't been done before, saves the original value of
# in the variable SAGE_ORIG_$varname (if was unset, then this
#is taken into account as well).
#
#If is not given, then is exported and its value and, if this
#hasn't been done before, its value is saved in the same way as above.
#(note that exporting an unset variable preserves its unset status)
#
#The fact that the variable has been stored is recorded by prepending
# to the exported environment variable $SAGE_ENV_RESTORE
sage_export ()
{
local varname="$1"
local backup="SAGE_ORIG_$varname"
if [ "$SAGE_ENV_RESTORE" == "${SAGE_ENV_RESTORE/$varname}" ]; then
export SAGE_ENV_RESTORE=$varname:$SAGE_ENV_RESTORE
if [ -z ${varname+x} ]; then
export ${backup}
else
local backup_value
eval backup_value="\$$varname"
export ${backup}="$backup_value"
fi
fi
if (( $# > 1 )); then
local value="$2"
export $varname="$value"
else
export $varname
fi
}
#sage_restore
#
#restores environment variable values previously stored by sage_export and
#removes the record that these variables were recorded.
sage_restore ()
{
#apparently IFS is already magically a local variable
IFS=:
for varname in $SAGE_ENV_RESTORE; do
local backup="SAGE_ORIG_$varname"
local value
eval value="\$$backup"
if [ -z ${backup+x} ]; then
unset $varname
else
export $varname="$value"
fi
unset $backup
done
unset SAGE_ENV_RESTORE
}