Zsh Shell Functions to export
and unset
all variables from env files located in the active working directory from which the commands are being executed.
Copy the two functions into your ~/.zshrc
, ~/.bashrc
, etc. and run source ~/.zshrc
etc. to refresh your shell configuration, use source ~/.zshrc
, etc.
You can now call set-env
to export all variables from the given filename (e.g., set-env .env
) and unset-env
(e.g., unset-env .env
) to unset the environment variables.
set-env() {
if [[ -f $1 ]]; then
echo "Environment file '$1' found. Setting variables..."
while IFS='=' read -r var value || [[ -n $value ]]; do
if [[ -n $var && -n $value && $var != \#* ]]; then
if printenv | grep -q "^$var="; then
echo "$var is already set. Overwriting..."
else
echo "Setting $var"
fi
export "$var=$value"
fi
done < $1
else
echo "Environment file '$1' not found."
fi
}
unset-env() {
if [[ -f $1 ]]; then
echo "Environment file '$1' found. Unsetting variables..."
while IFS= read -r line || [[ -n $line ]]; do
var="${line%%=*}"
if [[ -n $var && $var != \#* ]]; then
if printenv | grep -q "^$var="; then
echo "Unsetting $var"
unset $var
else
echo "$var is not set or already unset."
fi
fi
done < <(grep -Ev "^(#|$)" $1)
else
echo "Environment file '$1' not found."
fi
}