Skip to content

Instantly share code, notes, and snippets.

@imankulov
Created December 2, 2012 09:33
Show Gist options
  • Save imankulov/4187954 to your computer and use it in GitHub Desktop.
Save imankulov/4187954 to your computer and use it in GitHub Desktop.
Bash set_var / unset_var functions
#!/bin/bash
# function `set_var` sets a variable with a possiblity to restore previous
# value back with `unset_var`
#
# Can be used to safely initialize/uninitialize environment in python
# virtualenvwrapper and friends
#
#roman@home:~$ foo=1
#roman@home:~$ set_var foo 2
#roman@home:~$ set_var bar 3
#roman@home:~$ echo $foo $bar
#2 3
#roman@home:~$ unset_var foo
#roman@home:~$ unset_var bar
#roman@home:~$ echo $foo $bar
#1
function set_var() {
export OLD_$1=${!1}
export $1=$2
}
function unset_var() {
old_var_name="OLD_$1"
test -z "$old_var_name" && unset $1 || export $1=${!old_var_name}
unset OLD_$1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment