Skip to content

Instantly share code, notes, and snippets.

@thatguychrisw
Created January 17, 2018 21:18
Show Gist options
  • Save thatguychrisw/aab64ef4270363af2a0f037332715422 to your computer and use it in GitHub Desktop.
Save thatguychrisw/aab64ef4270363af2a0f037332715422 to your computer and use it in GitHub Desktop.
Will keep trying indefinitely till a postgres database is available, helpful when scripts depend on docker-compose up
+#!/bin/bash
+
+if [ "$#" -lt 2 ]; then
+ echo "Usage: wait-for-db.sh [host] [port] [database]"
+ exit 1
+fi
+
+host="$1"
+port="$2"
+database="$3"
+waited=0
+delay=2
+
+source .env
+
+export PGPASSWORD=$DB_PASSWORD
+export PGUSER=$DB_USERNAME
+
+function try () {
+ return `psql -h $host -lq 2>/dev/null | cut -d \| -f 1 | grep -qw $database`
+}
+
+until try
+do
+ echo "Waiting for database to initialize... ${waited}s"
+ sleep "$delay"
+ waited=$(($waited + $delay))
+done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment