Ticket #9386: sage_restore.sh

File sage_restore.sh, 1.7 KB (added by nbruin, 7 years ago)

sage export/restore environment variable facility

Line 
1#sage_export <varname> [<value>]
2#
3#If <value> is given, sets <varname> to <value> and exports the variable.
4#Furthermore, if this hasn't been done before, saves the original value of
5#<varname> in the variable SAGE_ORIG_$varname (if <varname> was unset, then this
6#is taken into account as well).
7#
8#If <value> is not given, then <varname> is exported and its value and, if this
9#hasn't been done before, its value is saved in the same way as above.
10#(note that exporting an unset variable preserves its unset status)
11#
12#The fact that the variable has been stored is recorded by prepending
13#<varname> to the exported environment variable $SAGE_ENV_RESTORE
14
15sage_export ()
16{
17    local varname="$1"
18    local backup="SAGE_ORIG_$varname"
19    if [ "$SAGE_ENV_RESTORE" == "${SAGE_ENV_RESTORE/$varname}" ]; then
20        export SAGE_ENV_RESTORE=$varname:$SAGE_ENV_RESTORE
21        if [ -z ${varname+x} ]; then
22            export ${backup}
23        else
24            local backup_value
25            eval backup_value="\$$varname"
26            export ${backup}="$backup_value"
27        fi
28    fi
29    if (( $# > 1 )); then
30        local value="$2"
31        export $varname="$value"
32    else
33        export $varname
34    fi
35}
36
37#sage_restore
38#
39#restores environment variable values previously stored by sage_export and
40#removes the record that these variables were recorded.
41
42sage_restore ()
43{
44    #apparently IFS is already magically a local variable 
45    IFS=:
46    for varname in $SAGE_ENV_RESTORE; do
47        local backup="SAGE_ORIG_$varname"
48        local value
49        eval value="\$$backup"
50        if [ -z ${backup+x} ]; then
51            unset $varname
52        else
53            export $varname="$value"
54        fi
55        unset $backup
56    done
57    unset SAGE_ENV_RESTORE
58}