Skip to content

Instantly share code, notes, and snippets.

@ycku
Last active July 29, 2021 05:38
Show Gist options
  • Save ycku/eb7dd0249e0c4ebf11f2ab17ee42f1a2 to your computer and use it in GitHub Desktop.
Save ycku/eb7dd0249e0c4ebf11f2ab17ee42f1a2 to your computer and use it in GitHub Desktop.
Retrieve connection info from PostgreSQL connection string
#!/bin/bash
str='postgresql://dbri@cxlitstaget01:5432/cxlimq_bm'
str='postgresql://dbir@cxlitstage01/cxlimq_bm'
str='postgresql://cxlitstage01:5432/cxlimq_bm'
regex='postgresql://(.*)@(.*):([0-9]*)/(.*)'
[[ $str =~ $regex ]]
if [ "$str" = "${BASH_REMATCH[0]}" ]; then
echo "MATCH: ${BASH_REMATCH[0]}"
echo "PGUSER: ${BASH_REMATCH[1]}"
echo "PGHOST: ${BASH_REMATCH[2]}"
echo "PGPORT: ${BASH_REMATCH[3]}"
echo "PGDATABASE: ${BASH_REMATCH[4]}"
fi
regex='postgresql://(.*)@(.*)/(.*)'
[[ $str =~ $regex ]]
if [ "$str" = "${BASH_REMATCH[0]}" ]; then
echo "MATCH: ${BASH_REMATCH[0]}"
echo "PGUSER: ${BASH_REMATCH[1]}"
echo "PGHOST: ${BASH_REMATCH[2]}"
echo "PGPORT: (not found) 5432"
echo "PGDATABASE: ${BASH_REMATCH[3]}"
fi
regex='postgresql://(.*)/(.*)'
[[ $str =~ $regex ]]
if [ "$str" = "${BASH_REMATCH[0]}" ]; then
echo "MATCH: ${BASH_REMATCH[0]}"
echo "PGUSER: (not found) (not set)"
echo "PGHOST: ${BASH_REMATCH[1]}"
echo "PGPORT: (not found) (5432)"
echo "PGDATABASE: ${BASH_REMATCH[2]}"
fi
regex='postgresql://(.*):([0-9]*)/(.*)'
[[ $str =~ $regex ]]
if [ "$str" = "${BASH_REMATCH[0]}" ]; then
echo "MATCH: ${BASH_REMATCH[0]}"
echo "PGUSER: (not found) (not set)"
echo "PGHOST: ${BASH_REMATCH[1]}"
echo "PGPORT: ${BASH_REMATCH[2]}"
echo "PGDATABASE: ${BASH_REMATCH[3]}"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment