Last active
July 26, 2026 17:50
-
-
Save gtrabanco/1b10af600b4bd84b0c356138030aec23 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| #!/usr/bin/env bash | |
| # Load secrets from a .env file as exported vars, and redact them from `env`. | |
| # Source this from ~/.bashrc: source ~/.bash_env_secrets.sh | |
| # Tracks which var names came from the .env file (redacted later). | |
| declare -ag ENV_SECRET_VARS=() | |
| ENV_FILE=${ENV_FILE:-${HOME}/.config/secrets/.env} | |
| load_env_secrets() { | |
| local envfile="${1:-${ENV_FILE}}" | |
| [ -f "$envfile" ] || return 0 | |
| ENV_SECRET_VARS=() | |
| local line key value | |
| while IFS= read -r line || [ -n "$line" ]; do | |
| # skip blank lines and comments | |
| [[ -z "$line" || "$line" =~ ^[[:space:]]*# ]] && continue | |
| # must look like KEY=VALUE | |
| [[ "$line" =~ ^[[:space:]]*([A-Za-z_][A-Za-z0-9_]*)=(.*)$ ]] || continue | |
| key="${BASH_REMATCH[1]}" | |
| value="${BASH_REMATCH[2]}" | |
| # strip surrounding quotes if present | |
| value="${value%\"}"; value="${value#\"}" | |
| value="${value%\'}"; value="${value#\'}" | |
| export "$key=$value" | |
| ENV_SECRET_VARS+=("$key") | |
| done < "$envfile" | |
| } | |
| # `env` override: same output, secret values replaced with <redacted> | |
| env() { | |
| local line key | |
| while IFS= read -r line; do | |
| key="${line%%=*}" | |
| local is_secret=0 | |
| for s in "${ENV_SECRET_VARS[@]}"; do | |
| [[ "$key" == "$s" ]] && { is_secret=1; break; } | |
| done | |
| if [ "$is_secret" -eq 1 ]; then | |
| echo "${key}=<redacted>" | |
| else | |
| echo "$line" | |
| fi | |
| done < <(command env) | |
| } | |
| load_env_secrets |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment