Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 system() 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.

like image 330
Cobra_Fast Avatar asked Dec 04 '25 01:12

Cobra_Fast


1 Answers

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.
pclose(check);

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).

like image 96
arunkumar Avatar answered Dec 06 '25 15:12

arunkumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!