$ workon myvenv
$ cat $VIRTUAL_ENV/bin/postactivate
#!/bin/bash
# This hook is run after this virtualenv is activated.
export DJANGO_DEBUG=True
export S3_KEY=mykey
export S3_SECRET=mysecret
$ echo $DJANGO_DEBUG
True
$ cat $VIRTUAL_ENV/bin/predeactivate
#!/bin/bash
# This hook is run before this virtualenv is deactivated.
unset DJANGO_DEBUG
$ deactivate
$ echo $DJANGO_DEBUG
$ cat $VIRTUAL_ENV/bin/postactivate
#!/bin/bash
# This hook is run after this virtualenv is activated.
if [[ -n $SOME_VAR ]]
then
export SOME_VAR_BACKUP=$SOME_VAR
fi
export SOME_VAR=apple
$ cat $VIRTUAL_ENV/bin/predeactivate
#!/bin/bash
# This hook is run before this virtualenv is deactivated.
if [[ -n $SOME_VAR_BACKUP ]]
then
export SOME_VAR=$SOME_VAR_BACKUP
unset SOME_VAR_BACKUP
else
unset SOME_VAR
fi
deactivate () {
... # Already existing code
# Restore the previous value of the ENV_VARIABLE on deactivation
# This code is executed when `deactivate` alias is called.
if [ ! "${1:-}" = "nondestructive" ] ; then
if [ -n "${_OLD_ENV_VARIABLE:-}" ] ; then
ENV_VARIABLE="${_OLD_ENV_VARIABLE:-}"
export ENV_VARIABLE
unset _OLD_ENV_VARIABLE
else
unset ENV_VARIABLE
fi
fi
}
在脚本的末尾添加行,在这里定义 "new value of the ENV_VARIABLE"。
这些行在激活虚拟环境时执行。
# Update or set a ENV_VARIABLE on activation
if [ -n "${ENV_VARIABLE:-}" ] ; then
_OLD_ENV_VARIABLE="${ENV_VARIABLE:-}"
fi
export ENV_VARIABLE="new value of the ENV_VARIABLE"
保存关闭文件。
结果 :
设定的结果一个新的环境变量:
:~$ echo $ENV_VARIABLE
:~$
:~$ source MY_ENV/bin/activate
(MY_ENV):~$
(MY_ENV):~$ echo $ENV_VARIABLE
new value of the ENV_VARIABLE
:~$
(MY_ENV):~$ deactivate
:~$
:~$ echo $ENV_VARIABLE
:~$
更新已经存在的环境变量:
:~$ export ENV_VARIABLE = "old value of the ENV_VARIABLE"
:~$
:~$ echo $ENV_VARIABLE
old value of the ENV_VARIABLE
:~$
:~$ source MY_ENV/bin/activate
(MY_ENV):~$
(MY_ENV):~$ echo $ENV_VARIABLE
new value of the ENV_VARIABLE
:~$
(MY_ENV):~$ deactivate
:~$
:~$ echo $ENV_VARIABLE
old value of the ENV_VARIABLE
:~$