我会非常担心仅仅运行一个命令。即使您知道它应该做什么,如果系统上有另一个同名的程序(无论是意外还是恶意),您可能会在简单地运行命令时产生奇怪的 - 并且可能非常糟糕的副作用。 AFAIK,正确执行此操作将是系统特定的,我可以建议的最好的方法是利用系统上的任何命令行 shell。
这两个问题的答案似乎为如何在 Linux 上执行此操作提供了很好的信息,我希望它对 BSD 也有效。它甚至可能对 Mac OS X 也有效,但我不知道,因为我不熟悉 Mac OS X 在命令行 shell 方面的默认设置。
How to check if command exists in a shell script?
Check if a program exists from a Bash script
答案似乎可以归结为使用type 命令,但您应该阅读答案中的详细信息。对于 Windows,快速搜索会发现:
Is there an equivalent of 'which' on the Windows command line?
它似乎提供了几种不同的方法来解决 Windows 上的问题。所以,从那里,应该可以找出一个在 Windows 上运行的 shell 命令来告诉你某个特定的命令是否存在。
不过,不管操作系统如何,您需要做的就是类似
bool commandExists(string command)
{
import std.process, std.string;
version(linux)
return executeShell(format("type %s", command)).status == 0;
else version(FreeBSD)
return executeShell(format("type %s", command)).status == 0;
else version(Windows)
static assert(0, "TODO: Add Windows magic here.");
else version(OSX)
static assert(0, "TODO: Add Mac OS X magic here.");
else
static assert(0, "OS not supported");
}
可能在某些系统上,您实际上必须解析命令的输出以查看它是否为您提供了正确的结果,而不是查看状态。不幸的是,这正是那种非常特定于系统的事情。