Skip to content

Instantly share code, notes, and snippets.

@Fmstrat
Last active September 4, 2020 03:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Fmstrat/ea6287a6d60e3e5f6c73e3bdd2f62331 to your computer and use it in GitHub Desktop.
Save Fmstrat/ea6287a6d60e3e5f6c73e3bdd2f62331 to your computer and use it in GitHub Desktop.
.pgpass with aliases for psql
alias:host:port:db:user:pass
alias2:host2:port2:db2:user2:pass2
#!/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
@jamesidw
Copy link

jamesidw commented Sep 4, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment