Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 781
Brian Vandenberg Avatar asked Dec 16 '22 14:12

Brian Vandenberg


2 Answers

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.

like image 186
Daniel DiPaolo Avatar answered Jan 02 '23 20:01

Daniel DiPaolo


Or just:

type -P awk   # returns the first matched binary called 'awk' in current PATH
like image 24
tulop Avatar answered Jan 02 '23 18:01

tulop