Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Bash function for switching asdf postgres versions and stopping/starting servers
function switch_pg {
local version_to_run=$1
local currently_running_version=$(psql --no-psqlrc -t -c 'show server_version;' postgres | xargs)
# check if you're erroneously switching to the same version
if [ "$version_to_run" = "$currently_running_version" ]; then
echo "Postgres $version_to_run is already running."
return 1
fi
echo Switching from $currently_running_version to $version_to_run
# stop the currently running postgres server
$HOME/.asdf/installs/postgres/$currently_running_version/bin/pg_ctl \
-D $HOME/.asdf/installs/postgres/$currently_running_version/data \
stop
# start the server to be started
$HOME/.asdf/installs/postgres/$version_to_run/bin/pg_ctl \
-D $HOME/.asdf/installs/postgres/$version_to_run/data \
start
# switch the global asdf version, this ensures that `psql` is shimmed to the right version-directory
asdf global postgres $version_to_run
}
@jbranchaud

This comment has been minimized.

Copy link
Owner Author

@jbranchaud jbranchaud commented Jan 15, 2021

You run it like so, assuming you have a couple different postgres versions installed with asdf:

$ asdf list postgres
  12.3
  13.1

$ postgres -V
postgres (PostgreSQL) 12.3

$ switch_pg 13.1
Switching from 13.1 to 12.3
...
server stopped
...
server started
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment