1
0
Fork 0
mirror of https://github.com/notwa/rc synced 2024-11-05 08:29:02 -08:00
rc/sh/witch

54 lines
972 B
Bash
Executable file

#!/usr/bin/env sh
# YES_ZSH YES_BASH YES_DASH YES_ASH
### @ witch
### this is a personal rewrite of `which` from Debian.
### the original version didn't run on certain shells,
### and inherited inconsistent behaviors from getopts.
set -ef
all=0
for flag; do
case "$flag" in
(--) shift; break;;
(-?*)
shift
while flag="${flag#?}"; [ -n "$flag" ]; do
case "$flag" in
(a*) all=1;;
(*)
printf >&2 'Illegal option: -%.1s\n' "$flag"
printf 'Usage: %s\n' "$0 [-a] args"
exit 2;;
esac
done;;
(*) break
esac
done
[ "$#" != 0 ] && res=1 || res=0
IFS=:
for prog; do
err=1
case "$prog" in
(*/*)
if [ -f "$prog" ] && [ -x "$prog" ]; then
printf %s\\n "$prog"
err=0
fi;;
(*)
set -- $(printf %s: "$PATH")
for sub; do
[ -n "$sub" ] || sub=.
if [ -f "$sub/$prog" ] && [ -x "$sub/$prog" ]; then
printf %s\\n "$sub/$prog"
err=0
[ "$all" = 1 ] || break
fi
done;;
esac
[ "$err" = 0 ] || res=1
done
exit "$res"