Last active
March 27, 2022 22:25
-
-
Save leagris/a30317afae8eec2f98e922ba666d1807 to your computer and use it in GitHub Desktop.
Bash implementation of debianutils:which
This file contains hidden or 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 bash | |
IFS=:;if (($#>0))&&[ "${1:0:1}" == - ];then if [ "$1" != -a ];then printf >&2 'Illegal option %s\nUsage: which [-a] args\n' "$1";exit 2;else b=1;fi;shift;fi;read -rd '' -a g < <(printf %s:\\0 "$PATH");while (($# > 0));do f=0;for d in "${g[@]}";do e="$d/$1";while [[ -L $e && "$(ls -l "$e")" =~ -\>\ (.*) ]];do e="${BASH_REMATCH[1]}";done;if [[ -f $e && -x $e ]];then f=1;echo "$d/$1";((b))||break;fi;done;((f))||c=1;shift;done;exit $c |
This file contains hidden or 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 bash | |
# | |
# @name | |
# which - locate a command | |
# | |
# @version | |
# 1.1.0 | |
# | |
# @date | |
# 2019-05-28 | |
# | |
# @author | |
# Léa Gris <[email protected]> | |
# | |
# @license | |
# WTFPL http://www.wtfpl.net/ | |
# | |
# @synopsis | |
# which [-a] filename ... | |
# | |
# @description | |
# Bash implementation of debianutils:which | |
# Behaves exactly like the native implementation | |
# | |
# @usage | |
# see https://manpages.debian.org/stretch/debianutils/which.1.en.html | |
function bash_which() { | |
# locate a command | |
local -i opt_a=0 | |
if (($# > 0)) && [[ ${1:0:1} == - ]]; then | |
if [[ $1 != -a ]]; then | |
printf >&2 'Illegal option %s\nUsage: which [-a] args\n' "$1" | |
return 2 | |
else | |
opt_a=1 | |
fi | |
shift | |
fi | |
local IFS=: | |
local -a path_arr | |
read -rd '' -a path_arr < <(printf %s:\\0 "${PATH}") | |
local -i rc=0 | |
while (($# > 0)); do | |
local -i found=0 | |
local dir | |
for dir in "${path_arr[@]}"; do | |
local path="${dir}/${1}" | |
while [[ -L ${path} && "$(ls -l "${path}")" =~ -\>[[:space:]](.*) ]]; do | |
path="${BASH_REMATCH[1]}" | |
done | |
if [[ -f ${path} && -x ${path} ]]; then | |
found=1 | |
echo "${dir}/${1}" | |
((opt_a)) || break | |
fi | |
done | |
((found)) || rc=1 | |
shift | |
done | |
return "${rc}" | |
} | |
bash_which "${@}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment