Cobra_Fast Cobra_Fast - 9 days ago 5x
Linux Question

How to check if command is available or existant?

I am developing a console application in C on linux.

Now an optional part of it (its not a requirement) is dependant on a command/binary being available.

If I check with

I'm getting
sh: command not found
as unwanted output and it detects it as existent. So how would I check if the command is there?

Not a duplicate of Check if a program exists from a Bash script since I'm working with C, not BASH.


To answer your question about how to discover if the command exists with your code. You can try checking the return value.

int ret = system("ls --version > /dev/null 2>&1"); //The redirect to /dev/null ensures that your program does not produce the output of these commands.
if (ret == 0) {
    //The executable was found.

You could also use popen, to read the output. Combining that with the whereis and type commands suggested in other answers -

char result[255];
FILE* fp = popen("whereis command", "r");
fgets(result, 255, fp);
//parse result to see the path of the bin if it has been found.

Or using type:

FILE* fp = popen("type command" , "r"); 

The result of the type command is a bit harder to parse since it's output varies depending on what you are looking for (binary, alias, function, not found).