- 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/bashset -euo pipefail # Load .envif [ -f .env ];thenset -a source .env set +a fiif [[ $#-eq 0 ]];then# No args → default psqlset -- psql -U "$POSTGRES_USER" -d "$POSTGRES_DB"elif [[ "$1"== -*||"$1"=="psql" ]];then# Remove explicit "psql" so we don't duplicate itif [[ "$1"=="psql" ]];thenshiftfi args=(psql) # Append -U only if missingif!printf'%s\n'"$@"| grep -Eq '(^| )-U |--username=';then args+=("-U""$POSTGRES_USER") fi# Append -d only if missingif!printf'%s\n'"$@"| grep -Eq '(^| )-d |--dbname=';then args+=("-d""$POSTGRES_DB") fiset -- "${args[@]}""$@"fi# Execute in dockerif [[ !-t 0 ]];thenexec docker compose exec -T postgres "$@"elseexec 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.