Using ZSH to switch between homebrew versions

zsh homebrew

2009-10-16 03:50:23 +0000

Lately I’ve taken a liking to homebrew. It’s the most attractive package management system on OS X that I’ve seen, and it’s simplicity makes it fun to hack. It it based on the tools that I use every day, Ruby and Git.

Because of this, and the array of existing formulae (that’s what it calls the ruby files it uses to build packages) to learn from, I’ve started to contribute.

I use homebrew for work, so I like to keep my production version (which is pulled straight from the official repo) separate from my fork, which I do my hacking on. By doing this, I can test formulae, and squash bugs in a clean environment, while using the official version for non-homebrew work.

To switch between these, I use a couple functions in my zshrc file that lets me switch between them (I have the official checkout in /usr/local and my version in ~/Projects):

function use_my_brew {
  path=(${path:#/usr/local/bin})
  path=(${path:#/usr/local/sbin})
  path=($HOME/Projects/homebrew/bin $HOME/Projects/homebrew/sbin $path)
}

function use_mxcl_brew {
  path=(${path:#$HOME/Projects/homebrew/bin})
  path=(${path:#$HOME/Projects/homebrew/sbin})
  path=(/usr/local/bin /usr/local/sbin $path)
}

The syntax is a bit strange if you’re new to ZSH, but I encourage you to check out the manual for more information.

Basically, the ${path:#<value>} form takes the path variable, which is an array, and removes entries matching <value>

Then, I add the other homebrew paths to the beginning of the array in the third line of each function.

Hint: You can use this form to test the presence of an item in an array by using the (M) flag, which does the opposite and removes NON matching elements from the array, leaving only those elements that are matched:

[[ -x ${(M)path:#$HOME/Projects/homebrew/bin} ]] && echo "using personal"

This will echo “using personal” if /Users/caleb/Projects/homebrew/bin is in the path.

blog comments powered by Disqus