Skip to content

Instantly share code, notes, and snippets.

@bulletinmybeard
Last active March 6, 2024 09:30
Show Gist options
  • Save bulletinmybeard/d1bd0f479776689061f1238c645a69cb to your computer and use it in GitHub Desktop.
Save bulletinmybeard/d1bd0f479776689061f1238c645a69cb to your computer and use it in GitHub Desktop.
Zsh Shell Functions to `export` and `unset` all variables from environment files in the current shell session

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.

Usage

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
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment