4

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.

Brian Vandenberg
  • 4,011
  • 2
  • 37
  • 53

3 Answers3

7

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.

Daniel DiPaolo
  • 55,313
  • 14
  • 116
  • 115
3

Or just:

type -P awk   # returns the first matched binary called 'awk' in current PATH
ijoseph
  • 6,505
  • 4
  • 26
  • 26
tulop
  • 31
  • 1
  • 1
    That's not a bad solution, but it is specific to bash. Also, it isn't functionally any different than 'which X'. However, not a bad suggestion. – Brian Vandenberg Apr 28 '11 at 15:41
2

An alternative solution is

find $(echo $PATH|tr : \ ) -maxdepth 0 -executable -name Executable

Where Executable is the name of the wanted application. For example:

find $(echo $PATH|tr : \ ) -maxdepth 0 -executable -name awk

returns

/usr/bin/awk
/bin/awk
kdubs
  • 1,596
  • 1
  • 21
  • 36
Tobias
  • 835
  • 1
  • 6
  • 11