binfind

find the path of a binary in your PATH using only bash

The tool which(1) has many different implementations on many different operating systems. Because of this, its output and return codes are not well-defined, and should not be trusted in the context of a script. However, it is often desirable to determine if an executable exists on a filesystem, without having to fork the executable itself to test.

The algorithm which(1) uses is fairly simple: loop over all paths found in the environmental variable PATH, and test for the existence, and executable bit, of the binary in question.

The function below will search your PATH for the binary name given as the first argument, and print the full path of the first binary found and return 0 if it is successful. Otherwise, it won’t print anything, and will return 1.

binfind() {
    local paths path
    IFS=: read -a paths <<< "$PATH"
    for path in "${paths[@]}"; do
        path=${path:-.}/$1
        if [[ -x $path ]]; then
            echo "$path"
            return 0
        fi
    done
    return 1
}

Example usage

$ binfind echo
/bin/echo
$ binfind clang
/usr/bin/clang
$ binfind foobar
$ echo $?
1