-
Notifications
You must be signed in to change notification settings - Fork 0
Postgres Convenience Script
Beau Barker edited this page Dec 1, 2025
·
4 revisions
For development, add the following script to make it easy to run psql inside the container:
db/bin/postgres
#!/bin/bash
set -euo pipefail
# Load .env
if [ -f .env ]; then
set -a
source .env
set +a
fi
if [[ $# -eq 0 ]]; then
# No args → default psql
set -- psql -U "$POSTGRES_USER" -d "$POSTGRES_DB"
elif [[ "$1" == -* || "$1" == "psql" ]]; then
# Remove explicit "psql" so we don't duplicate it
if [[ "$1" == "psql" ]]; then
shift
fi
args=(psql)
# Append -U only if missing
if ! printf '%s\n' "$@" | grep -Eq '(^| )-U |--username='; then
args+=("-U" "$POSTGRES_USER")
fi
# Append -d only if missing
if ! printf '%s\n' "$@" | grep -Eq '(^| )-d |--dbname='; then
args+=("-d" "$POSTGRES_DB")
fi
set -- "${args[@]}" "$@"
fi
# Execute in docker
if [[ ! -t 0 ]]; then
exec docker compose exec -T postgres "$@"
else
exec docker compose exec -it postgres "$@"
fiMake it executable:
chmod +x db/bin/postgresTo connect interactively (from the db directory):
bin/postgresExample output:
psql (17.5 (Debian 17.5-1.pgdg120+1))
Type "help" for help.
app=#
🗒️ By default,
bin/postgresopens apsqlshell. You can also run other commands in the container likebin/postgres bashif needed, or psql explicitly withbin/postgres psql.
You can also run SQL directly without opening an interactive shell:
bin/postgres -c 'select * from movie;'✅ Because bin/postgres defaults to psql, you don’t need to type psql
explicitly.