Created
January 13, 2017 03:39
-
-
Save killtw/73542650063f59817cbaebf747aa1583 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
function uri_parser() { | |
# uri capture | |
uri="$@" | |
# safe escaping | |
uri="${uri//\`/%60}" | |
uri="${uri//\"/%22}" | |
# top level parsing | |
pattern='^(([a-z]{3,5})://)?((([^:\/]+)(:([^@\/]*))?@)?([^:\/?]+)(:([0-9]+))?)(\/[^?]*)?(\?[^#]*)?(#.*)?$' | |
[[ "$uri" =~ $pattern ]] || return 1; | |
# component extraction | |
uri=${BASH_REMATCH[0]} | |
uri_schema=${BASH_REMATCH[2]} | |
uri_address=${BASH_REMATCH[3]} | |
uri_user=${BASH_REMATCH[5]} | |
uri_password=${BASH_REMATCH[7]} | |
uri_host=${BASH_REMATCH[8]} | |
uri_port=${BASH_REMATCH[10]} | |
uri_path=${BASH_REMATCH[11]} | |
uri_query=${BASH_REMATCH[12]} | |
uri_fragment=${BASH_REMATCH[13]} | |
# path parsing | |
count=0 | |
path="$uri_path" | |
pattern='^/+([^/]+)' | |
while [[ $path =~ $pattern ]]; do | |
eval "uri_parts[$count]=\"${BASH_REMATCH[1]}\"" | |
path="${path:${#BASH_REMATCH[0]}}" | |
let count++ | |
done | |
# query parsing | |
count=0 | |
query="$uri_query" | |
pattern='^[?&]+([^= ]+)(=([^&]*))?' | |
while [[ $query =~ $pattern ]]; do | |
eval "uri_args[$count]=\"${BASH_REMATCH[1]}\"" | |
eval "uri_arg_${BASH_REMATCH[1]}=\"${BASH_REMATCH[3]}\"" | |
query="${query:${#BASH_REMATCH[0]}}" | |
let count++ | |
done | |
# return success | |
return 0 | |
} | |
uri_parser "$1" | |
echo DB_HOST=$uri_host | |
echo DB_PORT=$uri_port | |
echo DB_DATABASE=$uri_path | |
echo DB_USERNAME=$uri_user | |
echo DB_PASSWORD=$uri_password |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment