Last Updated: February 25, 2016
·
487
· destructuring

Prune PATH based on some criteria

Maintaining multiple MacPorts distros and a homebrew means strictly separating them when building, installing ports/bew/bottles. Otherwise a homebrew may use the X11 config in a MacPorts and your distros are entangled.

Here's a fun function that returns $PATH stripped of directories that contain an executable. I run it like:

weed port brew

This removes all MacPorts and homebrew directories from my PATH so I can prepend just the install/build directories I need to work on a distro.

If I need to weed a specific distro, I put a dummy executable in it's install dir and weed it out like:

weed brew port_xmonad

Here's the weed function, shortened for publication.

 function weed {
  path="$PATH"

  for nm_cmd in "$@"; do
    old_ifs="$IFS"; IFS=":"; acc=""

    for p in $path; do
      [[ -x "$p/$nm_cmd" ]] || acc="$acc:$p" 
    done

    IFS="$old_ifs"; path="${acc#:}"
  done

  echo "$path"
}