Skip to content

Instantly share code, notes, and snippets.

@geoff-nixon
Created March 8, 2014 11:49
Show Gist options
  • Save geoff-nixon/9429311 to your computer and use it in GitHub Desktop.
Save geoff-nixon/9429311 to your computer and use it in GitHub Desktop.
brew which -- derefernce homebrew's symlinks.
#!/usr/bin/env sh # "brew which" -- derefernce paths for homebrew symlinks.
# "brew exec" -- exec these instead of printing/returning.
# G. Nixon 2014. Public domain or license of your choice; no warranty, etc.
iam=$(echo "$(basename "$0")" | cut -c6-10); cellar="$(brew --prefix)"
bin=$cellar/bin
optbin=$cellar/opt/bin
## Option parse.
for what; do case $1 in
-o | --opt*) OPT=1 && shift ;;
-s | --silent) SILENT=1 && shift ;;
# To do: find unlinked bins. Implement as... -a ? (Changes the meaning.) -u?
-a | --all) echo "brew $iam: -a flag is yet unimplemented." >&2 && exit 1 ;;
## Homebrew bug. brew does not pass -h | --help | help on to subcommands.
# -h | --help) echo 'Like $iam, but for path in Cellar.' >&2 && exit 1 ;;
-h | --*elp) echo "Like $iam, but for path in Cellar." >&2 && exit 1 ;;
'*') continue ;;
esac; done
## Work through a shell glob or multiple named arguments.
for what; do what="$(basename "$what")"
which="$(command -v "$what")"
binwhich="$bin/$what"
optbinwhich="$optbin/$what"
[ -x "$which" ] && [ -x "$binwhich" ] && # Executable in path and prefix.
[ -"$which"- = -"$binwhich"- ] || exit 1 # ...and they're the same.
cellarwhich="$(echo "$(readlink "$which")" | sed "s|^\.\.|$cellar|")"
whichwhat=$cellarwhich
[ -$OPT- = -1- ] && whichwhat=$optbinwhich # Override for -o flag.
[ -x "$cellarwhich" ] || exit 1 # Double check.
[ "$iam" = "exec" ] && exec $whichwhat ||
[ -$SILENT- = -1- ] || echo "$whichwhat"
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment