From: Simon Ruderich Date: Sun, 7 Mar 2010 20:49:57 +0000 (+0100) Subject: lib.sh: Improve installed() to work with more which. X-Git-Url: https://ruderich.org/simon/gitweb/?a=commitdiff_plain;h=f89f49df44d2d04eac338ead2d0843304414889e;p=config%2Fdotfiles.git lib.sh: Improve installed() to work with more which. Also add tests to check for different which implementations. --- diff --git a/lib.sh b/lib.sh index da00cce..49ce998 100644 --- a/lib.sh +++ b/lib.sh @@ -11,7 +11,7 @@ unset LS_COLORS # Check if the given program is installed. Returns 0 if it exists, 1 # otherwise; so it can be used in if. installed() { - which $1 | grep -E '^/' > /dev/null + which $1 2>&1 | perl -ne 'if (not m{^/}) { exit 1 }' } # Prints the current OS. Supported are Debian (debian), Gentoo (gentoo) and diff --git a/tests/lib.sh.test b/tests/lib.sh.test index 32bbd70..171c7c2 100644 --- a/tests/lib.sh.test +++ b/tests/lib.sh.test @@ -3,21 +3,41 @@ . ../lib.sh -# Tests for installed() with hopefully proper exit codes (1 if the program was -# not found). +# which with proper exit codes and output to stdout. +which() { + if [ $1 = ls ]; then + echo /bin/ls + else + echo no doesnt-exist in /usr/bin /bin /usr/sbin /sbin + (exit 1) + fi +} +echo stdout which +installed ls && echo ls installed +installed doesnt-exist && echo doesnt-exist installed + +# which with proper exit codes and output to stderr in case of an error. +which() { + if [ $1 = ls ]; then + echo /bin/ls + else + echo no doesnt-exist in /usr/bin /bin /usr/sbin /sbin >&2 + (exit 1) + fi +} +echo stderr which installed ls && echo ls installed installed doesnt-exist && echo doesnt-exist installed -# Simulate BSD `which` like on Mac OS X which doesn't use exit codes. -function which() { - echo Mac OS X which for $1 >&2 +# which with no proper exit codes and output to stdout in case of an error. +which() { if [ $1 = ls ]; then echo /bin/ls else echo no doesnt-exist in /usr/bin /bin /usr/sbin /sbin fi } -# Tests for installed() without exit codes. +echo stupid which installed ls && echo ls installed installed doesnt-exist && echo doesnt-exist installed diff --git a/tests/lib.sh.test.out b/tests/lib.sh.test.out index 9258e0f..7139144 100644 --- a/tests/lib.sh.test.out +++ b/tests/lib.sh.test.out @@ -1,7 +1,9 @@ +stdout which ls installed -Mac OS X which for ls +stderr which +ls installed +stupid which ls installed -Mac OS X which for doesnt-exist m4: generating 'tmp/test' from 'tmp/test.m4' with options '-DTEST=m4' ################################### # WARNING! DO NOT EDIT THIS FILE! #