As I've been working on my new Commitfie project, I stumbled upon a very basic issue regarding brew...

How do you know if a formula is linked or not?

The first idea I got was to use brew ls --version name_of_formula.

But this does not tell you if the formula is linked or not. In fact it will return true if the formula is just installed and not linked. Try the following code:

if $(brew ls --version name_of_formula &> /dev/null) ; then
	echo "Yeah\! It is installed\!"
else
	echo "Nooo... it is not installed..."
fi

So there might be something else...

But what's the difference between a linked formula and an unlinked formula?

Well it's pretty easy: a linked formula will be symlinked in $(brew --prefix)/bin. So we should be able to call $ name_of_formula --help or $ name_of_formula --version.

If we get something, it means the formula is linked. Try the following code:

if $(name_of_formula --help &> /dev/null) ; then
	echo "Yeah\! It is installed\!"
else
	echo "Nooo... it is not installed..."
fi

Important note: Sometimes, --help won't work, neither will --version. You should try other options such as -h, -v, etc. and find the one working for your formula.

And what if I want to check for formulae in batch?!

The fact that not all formulae use --help or --version makes it difficult to check for installed formulae in batch...

The other difference between a linked formula and an unlinked formula is the fact one will be present in $(brew --prefix)/bin while the other will not.

We could then list all the formulae in $(brew --prefix)/bin and grep the names of the ones we are looking for. Something like that:

ls -al $(brew --prefix)/bin | grep "name_of_formula"

As you can see, it would be really easy to store different name_of_formula in a FORMULA_ARRAY=( formula1 formula1 formula3 ) array and iteralte through it.

So might that be it? The real solution?

Try the following code

# Make sure all the brew dependencies are met
# You can change the names with your own formulae
BREW_DEPS=( imagesnap imagemagick whereami )
MISSING_BREW_DEPS=()

echo "\nChecking for \`brew\` dependencies:\n "
for dep in "${BREW_DEPS[@]}"
do
	if ls -al $(brew --prefix)/bin | grep "$dep" &> /dev/null ; then
		echo "Looking for $dep........ OK"
	else
		echo "Looking for $dep........ Error, not found!"
		MISSING_BREW_DEPS+=( $dep )
	fi
done

if [  ${#MISSING_BREW_DEPS[@]} -gt 0 ] ; then
	echo "\nThe following brew dependencies are missing: $MISSING_BREW_DEPS...\nYou must install them to continue the installation process..."
	exit 1
else
	echo "All the dependencies are met, you can safely continue the process :)"
fi

And that's it! You now can easily check if several formulae are linked and ready to be used.

Hope this helps! :)