Tag Archives: bash scripting

Testing for existence of programs via bash

For those of you who are into shell scripting, and want to know what in my opinion is the best way to test for whether programs exist or not, pay close attention.

In my humble opinion, the best way to test for the existence of a program, is to test the exit code of the previous command in an if loop.

Firstly, if you run a command that doesn’t exist, the exit code will always be ‘127′. If you don’t want to see the output of the command while testing for it, then just simply redirect all the output to /dev/null .

idontexist &> /dev/null
echo $?
127

Now, a friend suggested using this method for testing for programs in bash:

idontexist &> /dev/null || echo "You don't have 'idontexist'"; exit 1;

There are a few qualms with this. Firstly, depending on the program, if the program does not exit with the exit code of ‘0’, your shell script will then state ‘You don’t have ‘idontexist’ and then exit. However, you might actually have the program! Some programs exit with non-zero exit codes if you pass no arguments to them or even if you pass a ‘-h’ for a help argument to it. Also, since the echo statement is being terminated via the semicolon, ‘exit’ will then be executed. Ergo, this method looks great for just being a one liner, but if I want to test for the existence of a program, and if it doesn’t exist, and then exit with an error message displayed to the user, I highly suggest my following method:

idontexist &> /dev/null;

if [[ "$?" == "127" ]];
 then
     echo "'idontexist' appears to not be installed, check your PATH variable"; exit 1;
fi

More to come…