开发者

How to check if command is available or existant?

开发者 https://www.devze.com 2023-03-31 02:51 出处:网络
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.

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 s开发者_Python百科ystem() 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.
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).


You can use stat(2) on Linux(or any POSIX OS) to check for a file's existence.


Use which, you can either check the value returned by system() (0 if found) or the output of the command (no output equal not found):

$ which which
/usr/bin/which
$ echo $?
0
$ which does_t_exist
$ echo $?
1


If you run a shell, the output from "type commandname" will tell you whether commandname is available, and if so, how it is provided (alias, function, path to binary). You can read the documentation for type here: http://ss64.com/bash/type.html


I would just go through the current PATH and see whether you can find it there. That’s what I did recently with an optional part of a program that needed agrep installed. Alternately, if you don’t trust the PATH but have your own list of paths to check instead, use that.

I doubt it’s something that you need to check with the shell for whether it’s a builtin.

0

精彩评论

暂无评论...
验证码 换一张
取 消