Use find_working to prepare aliases.
[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 #          -q          Don't print path to prog.  Just exit 0 if found.
7 #          -x          Don't try to execute unreadable files.  Assume success.
8 #          -X          Don't try to execute unreadable files.  Assume failure.
9 #
10
11 args="-h -? --help"
12 quiet=0
13 unreadable=
14 while getopts ":a:qxX" opt; do
15   case $opt in
16     a) args="$OPTARG";;
17     q) quiet=1;;
18     x) unreadable=0;;
19     X) unreadable=1;;
20   esac
21 done
22 shift $((OPTIND-1))
23
24 prog="$1"; shift
25 if [ -z "$prog" ]; then
26   echo >&2 "Usage: find_working [options] <prog>"
27   echo >&2 "Options: -a <args>   Use arguments to test executable files.  Default --help."
28   echo >&2 "         -q          Don't print path to prog.  Just exit 0 if found."
29   echo >&2 "         -x          Don't try to execute unreadable files.  Assume success."
30   echo >&2 "         -X          Don't try to execute unreadable files.  Assume failure."
31   exit 1
32 fi
33
34 ret=
35 for path in ${PATH//:/ }; do
36   [ -x "$path/$prog" ] || continue
37
38   if [ -r "$path/$prog" ]; then
39     ldd "$path/$prog" 2>/dev/null | grep "not found" >/dev/null && continue
40     ret="$path/$prog"
41     break
42   elif [ -z "$unreadable" ]; then
43     "$path/$prog" $args 2>&1 | grep " $prog " >/dev/null || continue
44     ret="$path/$prog"
45     break
46   elif [ $unreadable = 0 ]; then
47     ret="$path/$prog"
48     break
49   elif [ $unreadable = 1 ]; then
50     continue
51   fi
52
53   exit 0
54 done
55
56 if [ -n "$ret" ]; then
57   [ $quiet = 0 ] && echo "$ret"
58   exit 0
59 fi
60
61 exit 100