Homebrew: Switching Keg Versions

Homebrew is an extraordinarily helpful tool to install and maintain system libraries. However, until I found out about the switch command, I didn’t have a straightforward way to switch between versions of a particular keg. Here’s how you can use it to switch between Postgres versions.

1. Select Your Version

If you run brew info postgres, the output will include a list of library versions. It’ll look something like this:

/usr/local/Cellar/postgresql/9.3.1 (2,928 files, 33.3M)
Built from source on 2014-04-29 at 15:35:23
/usr/local/Cellar/postgresql/9.3.4 (2,937 files, 32.1M)
Poured from bottle on 2014-04-15 at 22:00:59
/usr/local/Cellar/postgresql/9.4.1 (2,998 files, 33.4M)
Poured from bottle on 2015-02-05 at 17:40:55
/usr/local/Cellar/postgresql/9.4.4 (3,023 files, 33.5M)
Poured from bottle on 2015-06-13 at 19:01:33
/usr/local/Cellar/postgresql/9.5.5 (3,154 files, 35.1M) *
Poured from bottle on 2016-11-14 at 11:12:56

If you don’t see the version you need, it is possible to install it.

1a. Install your version.

If you haven’t tapped brew versions, you can do so by running brew tap homebrew/versions. This will add each version of each keg to the output when you run brew search postgres. From there, you can run brew install homebrew/versions/keg-version.

For example, to install Postgres 9.5.5, you would run brew install homebrew/versions/postgresql95.

2. Stop Any Running Services

If you are switching a keg that runs as a Homebrew service, you should stop it before switching to a new version. You can run brew services stop postgres to do so.

3. Switch to Your New Version

Now that we have the correct version installed and we have stopped any previous versions from running, we can switch to the correct version. All you have to do is run brew switch postgres. Under the hood, this actually performs two separate brew commands. First, it unlinks the old version, and then it links the new one.

4. Start the Service

If Step 2 applies to you, you’ll need to start the brew service again by running brew services start postgres.

Hopefully, this will help you move easily between different projects with different system dependencies.