Skip to content

Instantly share code, notes, and snippets.

@knadh
Created August 21, 2021 06:26
Show Gist options
  • Save knadh/5be315f877530eab3c8fc1fd2708d191 to your computer and use it in GitHub Desktop.
Save knadh/5be315f877530eab3c8fc1fd2708d191 to your computer and use it in GitHub Desktop.

Revisions

  1. knadh created this gist Aug 21, 2021.
    16 changes: 16 additions & 0 deletions parse-database-url-dsn-bash.sh
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,16 @@
    #!/usr/bin/env bash

    DATABASE_URL="postgres://MyPostgresUser:[email protected]:5432/MyPostgresDB"

    # `cut` is used to cut out the separators (:, @, /) that come matched with the groups.

    DATABASE_USER=$(echo $DATABASE_URL | grep -oP "postgres://\K(.+?):" | cut -d: -f1)
    DATABASE_PASSWORD=$(echo $DATABASE_URL | grep -oP "postgres://.*:\K(.+?)@" | cut -d@ -f1)
    DATABASE_HOST=$(echo $DATABASE_URL | grep -oP "postgres://.*@\K(.+?):" | cut -d: -f1)
    DATABASE_PORT=$(echo $DATABASE_URL | grep -oP "postgres://.*@.*:\K(\d+)/" | cut -d/ -f1)
    DATABASE_NAME=$(echo $DATABASE_URL | grep -oP "postgres://.*@.*:.*/\K(.+?)$")

    echo $DATABASE_USER
    echo $DATABASE_PASSWORD
    echo $DATABASE_HOST
    echo $DATABASE_PORT