Skip to content

Instantly share code, notes, and snippets.

@ulope
Last active January 18, 2023 15:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ulope/3c98c27f9e5770318ec5825c24f2db34 to your computer and use it in GitHub Desktop.
Save ulope/3c98c27f9e5770318ec5825c24f2db34 to your computer and use it in GitHub Desktop.
homebrew: make update accept formula names

homebrew: make update accept formula names

Homebrew has two commands with similar names - update and upgrade. Update is intended to update brew itself while upgrade is used to update individual formula.

This division is confusing to some.

Therefore here are shell functions for bash and zsh that reroute update to upgrade if a formula name is given.

# Put this into ~/.bashrc
brew() {
# This makes homebrew accept `brew update <formula>` instead of insisting on `upgrade`.
# When no parameters are given or all start with a dash it's assumed the user really wanted to use `update`.
has_name=0
for word in "${@:2}"; do
if [[ ! $word =~ -.* ]]; then
has_name=1
break
fi
done
if [[ ${@:1:1} == update && $has_name -gt 0 ]]; then
command brew upgrade "${@:2}"
else
command brew "${@}"
fi
}
# Put this into ~/.zshrc
brew() {
# This makes homebrew accept `brew update <formula>` instead of insisting on `upgrade`.
# When no parameters are given or all start with a dash it's assumed the user really wanted to use `update`.
# Explanation of the condition:
# - Is the first parameter `update`?
# - Count the number of array elements that start with `-`
# - `(M)` -> remove non matching elements
# - `#@[2,-1]` -> count (in this case matching) elements in `@` starting from second until end
# - `:#-*` -> match the elements against `-*` and remove non matching ones (due to the `(M)` flag)
# - Compare the number starting with `-` against the total
if [[ ${@[1]} == update && ${#@[2,-1]} -gt ${(M)#@[2,-1]:#-*} ]]; then
echo "Assuming update -> upgrade"
command brew upgrade "${@[2,-1]}"
else
command brew "${@}"
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment