Skip to content

Instantly share code, notes, and snippets.

@donfour
Last active October 11, 2025 18:48
Show Gist options
  • Select an option

  • Save donfour/527be1623617f7d467d306003e9977f2 to your computer and use it in GitHub Desktop.

Select an option

Save donfour/527be1623617f7d467d306003e9977f2 to your computer and use it in GitHub Desktop.
AI agent toolbox
PGHOST=
PGPORT=
PGDATABASE=
PGUSER=
PGPASSWORD=
#!/usr/bin/env bash
# postgres.sh — execute a SQL query using credentials from .env
set -euo pipefail
# Require query argument
if [ $# -eq 0 ]; then
echo "Usage: $0 \"SQL query\"" >&2
echo "Example: $0 \"SELECT now();\"" >&2
exit 1
fi
QUERY="$*"
ENV_FILE=".env"
# Load .env
if [[ ! -f "$ENV_FILE" ]]; then
echo "Error: .env file not found in current directory" >&2
exit 1
fi
set -a
# shellcheck disable=SC1091
source "$ENV_FILE"
set +a
# Verify required vars
for v in PGHOST PGPORT PGDATABASE PGUSER PGPASSWORD; do
if [[ -z "${!v:-}" ]]; then
echo "Error: $v not set in .env" >&2
exit 1
fi
done
# Run query
psql -X -v ON_ERROR_STOP=1 -qAt -P pager=off -c "$QUERY"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment