Skip to content

Instantly share code, notes, and snippets.

@aks
Created April 6, 2020 17:59
Show Gist options
  • Save aks/2e19f18b24b24c46d6d6d5a005551038 to your computer and use it in GitHub Desktop.
Save aks/2e19f18b24b24c46d6d6d5a005551038 to your computer and use it in GitHub Desktop.
Bash script for running multiple versions of `pg_ctl`, using `asdf` to manage the postgres versions
#!/usr/bin/env bash
PROG="${0##*/}"
DIR="${0%/*}"
current_pg_version() {
asdf current postgres | cut -d' ' -f1
}
DEFAULT_PG_VERSION=`current_pg_version`
usage() {
cat 1>&2 <<EOF
usage: $PROG [-h] [-n] [-v] [-V VERSION] [start | stop | status]
This is a multi-version proxy for running "pg_ctl" commands.
The default version is ${DEFAULT_PG_VERSION}.
Options:
-h show this help
-n show the commands but do not run them
-v talk more
-V VERSION Operate on this VERSION of postgres
EOF
exit
}
talk() { echo 1>&2 "$*" ; }
vtalk() { (( verbose )) && talk "$*" ; }
error() { talk "$*" ; exit 1 ; }
run() {
if (( norun )) ; then
talk "(norun) $*"
else
vtalk "--> $*"
$@
fi
}
while getopts 'hnvV:' opt ; do
case "$opt" in
h) usage ;;
n) norun=1 ;;
v) verbose=1 ;;
V) PG_VERSION="$OPTARG" ;;
esac
done
shift $(( OPTIND - 1))
# set the default version
PG_VERSION=${PG_VERSION:-$DEFAULT_PG_VERSION}
PG_DIR="$HOME/.asdf/installs/postgres/$PG_VERSION"
[[ -d "$PG_DIR" ]] || error "No such version installed: $PG_VERSION"
PG_BIN="$PG_DIR/bin"
PG_DATA="$PG_DIR/data"
PG_CTL="$PG_BIN/pg_ctl"
PG_LOGFILE="$HOME/log/postgres-$PG_VERSION.log"
if (( $# > 0 )) ; then
action="$1"
else
case $PROG in
*start) action=start ;;
*stop) action=stop ;;
*status) action=status ;;
*ctl) usage ;;
*) talk "Don't know what $PROG does" ; usage ;;
esac
fi
if [[ ! -e "$PG_LOGFILE" ]] ; then
logdir=`dirname $PG_LOGFILE`
run "mkdir -p $logdir"
run "touch $PG_LOGFILE"
run "chmod 1777 $PG_LOGFILE"
fi
run "$PG_CTL -D $PG_DATA -l $PG_LOGFILE $action"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment