Skip to content

Instantly share code, notes, and snippets.

@leagris
Last active March 27, 2022 22:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leagris/a30317afae8eec2f98e922ba666d1807 to your computer and use it in GitHub Desktop.
Save leagris/a30317afae8eec2f98e922ba666d1807 to your computer and use it in GitHub Desktop.
Bash implementation of debianutils:which
#!/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
#!/usr/bin/env bash
#
# @name
# which - locate a command
#
# @version
# 1.1.0
#
# @date
# 2019-05-28
#
# @author
# Léa Gris <lea.gris@noiraude.net>
#
# @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