Search code examples
perlbashshellcshtcsh

Shell test to see whether a binary is in your path


In csh, tcsh, bash, perl (etc) you can do tests on par with (not necessarily with the same syntax):

test -e PATH; # Does PATH exist
test -f PATH; # Is PATH a file
test -d PATH; # is PATh a directory
...

Does a similar construct exist for checking whether a binary is in your path? (and perhaps whether an alias, or even a built-in exist)

Obviously this can be done with something of the form:

#!/usr/bin/env bash
C=COMMAND;
test $(which $C) -o $(alias $C) && "$C exists"

or something similar in other shells/script languages.

The question isn't whether it's possible to test for the existence of a program, command, etc. The question is whether a built-in test exists or not.


Solution

  • Technically if you're just looking for stuff in the current PATH then the only real solution is the first portion of your second code block:

    which $C
    

    which is the only one that really fits your actual requirement of in the current PATH as whereis will search outside the path:

    whereis ... attempts to locate the desired program in a list of standard Linux places.

    from whereis(1)

    and alias of course has nothing to do with actual executables, but rather aliased commands within your shell environment

    So, really, you've got the right approach already, just be careful that you know that whereis may not be a helpful addition to that chain of tests.