Last active
November 16, 2015 16:10
-
-
Save nextrevision/3f1583eea12017f0838f to your computer and use it in GitHub Desktop.
Small script to unsource variables from a script or file. See http://nextrevision.github.io/2015/unsourcing-vars-files-in-bash/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash -e | |
if [ -z "$1" ]; then | |
echo "usage: unsource.sh vars.env" | |
elif [ ! -f "$1" ]; then | |
echo "No such file: ${1}" | |
else | |
__start_env=$(mktemp -t unsource.XXXXXX) | |
__end_env=$(mktemp -t unsource.XXXXXX) | |
env -i bash -e -c "declare -f | egrep '^\w' | cut -d' ' -f1 > ${__start_env}; \ | |
export | cut -d' ' -f3 | cut -d'=' -f1 >> ${__start_env}; \ | |
set -a; \ | |
$(export | cut -d' ' -f3- | grep '=' | tr '\n' ' ') source $1; \ | |
declare -f | egrep '^declare' | cut -d' ' -f3 | cut -d'=' -f1 > ${__end_env}; \ | |
export | cut -d' ' -f3 | cut -d'=' -f1 >> ${__end_env}" | |
for __target in $(diff ${__start_env} ${__end_env} | egrep '^>' | cut -d' ' -f2); do | |
unset ${__target} | |
echo "Cleared: ${__target}" | |
done | |
rm ${__start_env} ${__end_env} | |
unset __target | |
unset __start_env | |
unset __end_env | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Cool. What if
unsource
without parameters just reset you back to a clean environment?Also, any reason why I wouldn't just copy or symlink unsource.sh into /usr/local/bin and call directly?