Fixed argument handling in find_working.
[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 <args>   Use arguments to test executable files.  Default --help.
6 #          -A          Don't test arguments to executable files.
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 ":a:AqxX" opt; do
16   case $opt in
17     a) args="$OPTARG";;
18     A) args="";;
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 <args>   Use arguments to test executable files.  Default --help."
30   echo >&2 "         -A          Don't test arguments to executable files."
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 ret=
38 for path in ${PATH//:/ }; do
39   [ -x "$path/$prog" ] || continue
40
41   if [ -r "$path/$prog" ]; then
42     if [ -n "$args" ]; then
43       "$path/$prog" $args 2>&1 | grep " $prog " >/dev/null || continue
44     else
45       ldd "$path/$prog" 2>/dev/null | grep "not found" >/dev/null && continue
46     fi
47     ret="$path/$prog"
48     break
49   elif [ -z "$unreadable" ]; then
50     "$path/$prog" $args 2>&1 | grep " $prog " >/dev/null || continue
51     ret="$path/$prog"
52     break
53   elif [ $unreadable = 0 ]; then
54     ret="$path/$prog"
55     break
56   elif [ $unreadable = 1 ]; then
57     continue
58   fi
59
60   exit 0
61 done
62
63 if [ -n "$ret" ]; then
64   [ $quiet = 0 ] && echo "$ret"
65   exit 0
66 fi
67
68 exit 100