Skip to content

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 "$@"fi

Make it executable:

chmod +x db/bin/postgres

To connect interactively (from the db directory):

bin/postgres

Example output:

psql (17.5 (Debian 17.5-1.pgdg120+1)) Type "help" for help. app=# 

🗒️ By default, bin/postgres opens a psql shell. You can also run other commands in the container like bin/postgres bash if needed, or psql explicitly with bin/postgres psql.

🔹 Run Inline SQL Commands

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.

Clone this wiki locally