如何检查命令是否可用? [英] How to check if command is available or existant?

查看:126
本文介绍了如何检查命令是否可用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Linux上用C开发控制台应用程序。

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.

如果我使用 system()进行检查,则会得到 sh:命令不是找到作为不需要的输出,它将其检测为存在。那么我该如何检查命令是否存在?

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?

不是检查程序是否存在于Bash脚本中,因为我使用的是C而不是BASH 。

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

您也可以使用 popen ,以读取输出。结合其他答案中建议的whereis和type命令-

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

或使用以下类型:

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

type 命令的结果为
难于解析,因为它的输出取决于您要查找的内容(二进制,别名,函数,未找到)。

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

这篇关于如何检查命令是否可用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆