Skip to content

Instantly share code, notes, and snippets.

@jbranchaud
Last active July 6, 2022 17:37
Show Gist options
  • Save jbranchaud/3cda6be6e1dc69c6f55435a387018dac to your computer and use it in GitHub Desktop.
Save jbranchaud/3cda6be6e1dc69c6f55435a387018dac to your computer and use it in GitHub Desktop.
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
Copy link
Author

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