Last active
February 4, 2021 13:54
-
-
Save joshlk/f03b04cd00807d2ed8c2bdd53b439d66 to your computer and use it in GitHub Desktop.
`where` in the $PATH is an executable found. Bash/shell/unix script. Extends `which` to also print the $PATH index (GNU General Public License)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /bin/sh | |
set -ef | |
if test -n "$KSH_VERSION"; then | |
puts() { | |
print -r -- "$*" | |
} | |
else | |
puts() { | |
printf '%s\n' "$*" | |
} | |
fi | |
ALLMATCHES=0 | |
while getopts a whichopts | |
do | |
case "$whichopts" in | |
a) ALLMATCHES=1 ;; | |
?) puts "Usage: $0 [-a] args"; exit 2 ;; | |
esac | |
done | |
shift $(($OPTIND - 1)) | |
if [ "$#" -eq 0 ]; then | |
ALLRET=1 | |
else | |
ALLRET=0 | |
fi | |
case $PATH in | |
(*[!:]:) PATH="$PATH:" ;; | |
esac | |
for PROGRAM in "$@"; do | |
RET=1 | |
IFS_SAVE="$IFS" | |
IFS=: | |
case $PROGRAM in | |
*/*) | |
if [ -f "$PROGRAM" ] && [ -x "$PROGRAM" ]; then | |
puts "$PROGRAM" | |
RET=0 | |
fi | |
;; | |
*) | |
j=0 | |
for ELEMENT in $PATH; do | |
if [ -z "$ELEMENT" ]; then | |
ELEMENT=. | |
fi | |
if [ -f "$ELEMENT/$PROGRAM" ] && [ -x "$ELEMENT/$PROGRAM" ]; then | |
puts "$ELEMENT/$PROGRAM $j" | |
RET=0 | |
[ "$ALLMATCHES" -eq 1 ] || break | |
fi | |
j=$((j+1)) | |
done | |
;; | |
esac | |
IFS="$IFS_SAVE" | |
if [ "$RET" -ne 0 ]; then | |
ALLRET=1 | |
fi | |
done | |
exit "$ALLRET" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /bin/sh | |
# Where in the $PATH is `cp` picked up from?: entry 11 "/bin" | |
./where.sh cp | |
# > /bin/cp 11 | |
# Same input format as `which`: can take multipel inputs | |
./where.sh cp scp which | |
# > /bin/cp 11 | |
# > /usr/bin/scp 9 | |
# > /usr/bin/which 9 | |
# For comparision: | |
./which.sh cp scp which | |
# > /bin/cp | |
# > /usr/bin/scp | |
# > /usr/bin/which |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Slight modification of the
which
command source.