Last active
February 25, 2022 07:49
-
-
Save juliyvchirkov/d2c7ff01846157f58b1fc1f3a3b1e36c to your computer and use it in GitHub Desktop.
sh: mimics the core routine of GNU `which` command
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
#!/usr/bin/env sh | |
# | |
# Mimics the core routine of UNIX `which` command[1] | |
# | |
# Implemented on the top of shell builtins to provide the way | |
# to resolve external dependencies (commands) for shell scripts | |
# whether external `which` command available or not | |
# | |
# Designed to be fully `sh` compatible, strictly honors POSIX standards | |
# and completely meets Shell Command Language specification[2], thus | |
# can be safely utilized with any Bourne Family shell | |
# | |
# Developed by https://juliyvchirkov.github.io 2018-2022 under the MIT license | |
# | |
# Tested with `bash -r`, `dash -r` and `posh`[3] | |
# | |
# Get the last revision at https://gist.github.com/juliyvchirkov/d2c7ff01846157f58b1fc1f3a3b1e36c | |
# | |
# [1] https://www.freebsd.org/cgi/man.cgi?query=which | |
# [2] https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html | |
# [3] https://www.commandlinux.com/man-page/man1/posh.1.html | |
which() ( | |
[ "${1}" = "--" ] && shift | |
if [ $# -gt 0 ]; then | |
for path in $(IFS=: && printf "%s " ${PATH}); do | |
[ -x "${path}/${1}" ] && printf "%s/%s" "${path}" "${1}" && return 0 | |
done | |
return 1 | |
fi | |
printf >&2 "%s: %s [--] %s\n%s\n" "Usage" "which" "COMMAND" "Writes the full path of COMMAND to standard output." | |
return 1 | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment