Tidyup.
[profile.git] / opt / bin / find_working
1 #!/bin/bash
2 #
3 # find_working: Find a version of some tool in the PATH which actually runs.
4 # Usage: find_working [options] <prog>
5 # Options: -A          Don't test arguments to executable files.
6 #          -a <args>   Use arguments to test executable files.  Default --help.
7 #          -q          Don't print path to prog.  Just exit 0 if found.
8 #          -x          Don't try to execute unreadable files.  Assume success.
9 #          -X          Don't try to execute unreadable files.  Assume failure.
10 #
11
12 args="-h -? --help"
13 quiet=0
14 unreadable=
15 while getopts ":Aa:qxX" opt; do
16   case $opt in
17     A) args="";;
18     a) args="$OPTARG";;
19     q) quiet=1;;
20     x) unreadable=0;;
21     X) unreadable=1;;
22   esac
23 done
24 shift $((OPTIND-1))
25
26 prog="$1"; shift
27 if [ -z "$prog" ]; then
28   echo >&2 "Usage: find_working [options] <prog>"
29   echo >&2 "Options: -A          Don't test arguments to executable files."
30   echo >&2 "         -a <args>   Use arguments to test executable files.  Default --help."
31   echo >&2 "         -q          Don't print path to prog.  Just exit 0 if found."
32   echo >&2 "         -x          Don't try to execute unreadable files.  Assume success."
33   echo >&2 "         -X          Don't try to execute unreadable files.  Assume failure."
34   exit 1
35 fi
36
37 # Default args contain -? which might be interpreted as a glob.
38 set -o noglob
39
40 ret=
41 for path in ${PATH//:/ }; do
42   [ -x "$path/$prog" ] || continue
43
44   if [ -r "$path/$prog" ]; then
45     if [ -n "$args" ]; then
46       "$path/$prog" $args 2>&1 | grep "\\b$prog\\b" >/dev/null || continue
47     else
48       ldd "$path/$prog" 2>/dev/null | grep "not found" >/dev/null && continue
49     fi
50     ret="$path/$prog"
51     break
52   elif [ -z "$unreadable" ]; then
53     "$path/$prog" $args 2>&1 | grep "\\b$prog\\b" >/dev/null || continue
54     ret="$path/$prog"
55     break
56   elif [ $unreadable = 0 ]; then
57     ret="$path/$prog"
58     break
59   elif [ $unreadable = 1 ]; then
60     continue
61   fi
62
63   exit 0
64 done
65
66 if [ -n "$ret" ]; then
67   [ $quiet = 0 ] && echo "$ret"
68   exit 0
69 fi
70
71 exit 100