Last active
September 4, 2020 03:39
-
-
Save Fmstrat/ea6287a6d60e3e5f6c73e3bdd2f62331 to your computer and use it in GitHub Desktop.
.pgpass with aliases for psql
This file contains 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
alias:host:port:db:user:pass | |
alias2:host2:port2:db2:user2:pass2 |
This file contains 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
#!/usr/bin/env bash | |
# Create a ~/.pgapass file with lines: | |
# alias:host:port:db:user:pass | |
function usage() { | |
echo 'Usage: | |
psql --list|-l # Show all aliases | |
psql <alias> # Connect to alias' | |
} | |
if [ ! -f /usr/bin/psql ]; then | |
sudo apt install -y postgres-client | |
fi | |
if [ -z "${1}" ]; then | |
usage; | |
fi | |
case "${1}" in | |
--list|-l) | |
if [ -f ~/.pgapass ]; then | |
cat ~/.pgapass |sed 's/:.*//' |sort | |
fi | |
;; | |
*) | |
for LINE in $(cat ~/.pgapass); do | |
IFS=':' read -r ALIAS HOST PORT DB U P <<< "$LINE" | |
if [ "${ALIAS}" = "${1}" ]; then | |
echo "${HOST}:${PORT}:${DB}:${U}:${P}" > ~/.pgpass | |
chmod 600 ~/.pgpass | |
shift | |
PGPASSFILE=~/.pgpass /usr/bin/psql --host ${HOST} --user ${U} --port ${PORT} $@ ${DB} | |
rm -f ~/.pgpass | |
fi | |
done | |
;; | |
esac |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks! I've modified your script here: https://gist.github.com/jamesidw/0c66f5d1e78555144edb32f93b120997