In my CI-setup, I would like to make sure that the newest version of a given formula is installed, regardless of whether it is already installed or not.
I'm currently using something like:
brew update
brew install FORMULA || (brew upgrade FORMULA && brew cleanup FORMULA)
What are the pitfalls with this approach? Is there a nicer approach to the problem (e.g. by first querying whether FORMULA is already installed, rather than relying on brew install
to fail only if FORMULA is installed)?
I you want to install a Homebrew package if it does not already exist, and upgrade it otherwise, the best solution is to use Homebrew Bundle which is officially part of the Homebrew family. If that doesn't work for you, and you want to roll your own solution, you should reference at the suggestions below.
There are other situation where a brew install
might fail, other than a package already being installed. I'm not sure, but it doesn't look like the brew install
command emits an exit status other than 1
on failure, so you have two options:
stderr
for "not installed" and check against thatThe most common approach I've seen used for this purpose is to check if the package is installed with the command brew ls --versions
:
function install_or_upgrade {
if brew ls --versions "$1" >/dev/null; then
HOMEBREW_NO_AUTO_UPDATE=1 brew upgrade "$1"
else
HOMEBREW_NO_AUTO_UPDATE=1 brew install "$1"
fi
}
You'll want to use HOMEBREW_NO_AUTO_UPDATE=1
if you're installing multiple packages so that Homebrew does not try to update in between each install/upgrade.