diff options
author | dteske <dteske@FreeBSD.org> | 2013-07-10 22:45:07 +0000 |
---|---|---|
committer | dteske <dteske@FreeBSD.org> | 2013-07-10 22:45:07 +0000 |
commit | 68c057774b7e777ec9e33683d723d86e6b061b8d (patch) | |
tree | 0e0541d41bb14eb9f7cdff3e0421b27f64d7efb2 /usr.sbin | |
parent | 09dc6d910626afc52f9b718c253a1e89f916e73c (diff) | |
download | FreeBSD-src-68c057774b7e777ec9e33683d723d86e6b061b8d.zip FreeBSD-src-68c057774b7e777ec9e33683d723d86e6b061b8d.tar.gz |
Introduce a new [yet unused] function for [efficiently] getting the path to
an executable by-name without forking or using externals.
In a performance benchmark of 10,000 runs on circa 2006 hardware, f_which
out-performed `which' with an average completion time of ~2.5 seconds versus
~56 seconds.
This should be handy for future use (not that I make it a habit to call
`which' in a loop 10,000 times).
Diffstat (limited to 'usr.sbin')
-rw-r--r-- | usr.sbin/bsdconfig/share/common.subr | 29 |
1 files changed, 29 insertions, 0 deletions
diff --git a/usr.sbin/bsdconfig/share/common.subr b/usr.sbin/bsdconfig/share/common.subr index 6c0400a..985bf6b 100644 --- a/usr.sbin/bsdconfig/share/common.subr +++ b/usr.sbin/bsdconfig/share/common.subr @@ -212,6 +212,35 @@ f_have() f_quietly type "$@" } +# f_which $anything [$var_to_set] +# +# A fast built-in replacement for syntaxes such as foo=$( which bar ). In a +# comparison of 10,000 runs of this function versus which, this function +# completed in under 3 seconds, while `which' took almost a full minute. +# +# If $var_to_set is missing or NULL, output is (like which) to standard out. +# Returns success if a match was found, failure otherwise. +# +f_which() +{ + local __name="$1" __var_to_set="$2" + case "$__name" in */*|'') return $FAILURE; esac + local __p IFS=":" __found= + for __p in $PATH; do + local __exec="$__p/$__name" + [ -f "$__exec" -a -x "$__exec" ] && __found=1 && break + done + if [ "$__found" ]; then + if [ "$__var_to_set" ]; then + setvar "$__var_to_set" "$__exec" + else + echo "$__exec" + fi + return $SUCCESS + fi + return $FAILURE +} + # f_getvar $var_to_get [$var_to_set] # # Utility function designed to go along with the already-builtin setvar. |