Skip to content

Instantly share code, notes, and snippets.

@geoff-nixon
Last active August 29, 2015 14:13
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 geoff-nixon/ccbd5758d249e582d296 to your computer and use it in GitHub Desktop.
Save geoff-nixon/ccbd5758d249e582d296 to your computer and use it in GitHub Desktop.
#!/bin/sh ## which(1) written in pure POSIX shell.
## A `which` utility is *not* included in the POSIX standard.
## This version upports -s (silent) and -a (all), and -v (verbose).
## (c) 2015 Geoff Nixon. Public Domain; no warranty expressed or implied.
which(){
which_try=
which_result=
which_verbose=0
which_silent=0
which_usage(){ echo "usage: "$(basename "$0")" [-asv] program ..." >&2 ;}
which_error(){
[ $which_verbose = 1 ] &&
echo "$(basename "$0"): no $which_util in ($PATH)" >&2 || :
}
OPTIND=1; while getopts "ahsv?" which_opt; do
case "$which_opt" in
a) which_next=continue ;;
h) which_usage; exit 0 ;;
s) which_silent=1 ;;
v) which_verbose=1 ;;
\?) which_usage; exit 1 ;;
esac
done
shift $((OPTIND - 1))
which_try(){
echo "$PATH" | tr ':' '\n' | while read which_component; do
which_try="$which_component/$which_util"
[ -x "$which_try" ] && echo "$which_try" && break
done
}
for which_util; do :; done
[ -z "$which_util" ] && which_usage && exit 1
which_result="$(which_try "$which_util")"
[ -z "$which_result" ] && which_error && exit 1 ||
[ $which_silent = 1 ] && exit 0 || echo "$which_result" | uniq
}
which "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment