Skip to content

Instantly share code, notes, and snippets.

@nextrevision
Last active November 16, 2015 16:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nextrevision/3f1583eea12017f0838f to your computer and use it in GitHub Desktop.
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/
#!/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
@cllunsford
Copy link

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment