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