Use find_working to prepare aliases.
[profile.git] / opt / bin / find_working
diff --git a/opt/bin/find_working b/opt/bin/find_working
new file mode 100755 (executable)
index 0000000..cbbd82d
--- /dev/null
@@ -0,0 +1,61 @@
+#!/bin/bash
+#
+# find_working: Find a version of some tool in the PATH which actually runs.
+# Usage: find_working [options] <prog>
+# Options: -a <args>   Use arguments to test executable files.  Default --help.
+#          -q          Don't print path to prog.  Just exit 0 if found.
+#          -x          Don't try to execute unreadable files.  Assume success.
+#          -X          Don't try to execute unreadable files.  Assume failure.
+#
+
+args="-h -? --help"
+quiet=0
+unreadable=
+while getopts ":a:qxX" opt; do
+  case $opt in
+    a) args="$OPTARG";;
+    q) quiet=1;;
+    x) unreadable=0;;
+    X) unreadable=1;;
+  esac
+done
+shift $((OPTIND-1))
+
+prog="$1"; shift
+if [ -z "$prog" ]; then
+  echo >&2 "Usage: find_working [options] <prog>"
+  echo >&2 "Options: -a <args>   Use arguments to test executable files.  Default --help."
+  echo >&2 "         -q          Don't print path to prog.  Just exit 0 if found."
+  echo >&2 "         -x          Don't try to execute unreadable files.  Assume success."
+  echo >&2 "         -X          Don't try to execute unreadable files.  Assume failure."
+  exit 1
+fi
+
+ret=
+for path in ${PATH//:/ }; do
+  [ -x "$path/$prog" ] || continue
+
+  if [ -r "$path/$prog" ]; then
+    ldd "$path/$prog" 2>/dev/null | grep "not found" >/dev/null && continue
+    ret="$path/$prog"
+    break
+  elif [ -z "$unreadable" ]; then
+    "$path/$prog" $args 2>&1 | grep " $prog " >/dev/null || continue
+    ret="$path/$prog"
+    break
+  elif [ $unreadable = 0 ]; then
+    ret="$path/$prog"
+    break
+  elif [ $unreadable = 1 ]; then
+    continue
+  fi
+
+  exit 0
+done
+
+if [ -n "$ret" ]; then
+  [ $quiet = 0 ] && echo "$ret"
+  exit 0
+fi
+
+exit 100