[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Bug#218530: Conditional command execution



* Thomas Hood 

| What is the best way to run a command if and only if it is on the PATH?

findcommand() {
    while [ "$#" -ge 1 ]; do
        P="$PATH"
        while [ "$P" ]; do
            D=${P%%:*}
            P=${P#*:}
            if [ "$D" = "$P" ]; then
                P=
            fi
            if [ -z "$D" ]; then
                D=.
            fi
            if [ -x "$D/$1" ]; then
                echo "$D/$1"
                return
            fi
        done
        shift
    done
}

should do what command -v does.  (Actually, it does a bit more, as it
can do stuff like:

: tfheen@vawad ~ > findcommand foo bar baz xterm
/usr/X11R6/bin/xterm

(which is _very_ useful for me when I'm doing something approaching
per-user cross-host alternatives (similar to what update-alternatives
provides).)

-- 
Tollef Fog Heen                                                        ,''`.
UNIX is user friendly, it's just picky about who its friends are      : :' :
                                                                      `. `' 
                                                                        `-  



Reply to: