如何以编程方式检查程序是否存在?
假设我正在编写一些依赖于外部程序的东西,例如 svn
。如何自动检查它们是否存在,以便在它们不存在时打印有用的错误消息?迭代PATH
是可能的,但很难优雅和高效。有更清洁的解决方案吗?
我在引导脚本中看到过这种行为,但我不记得在哪里。它看起来有点像这样:
checking for gcc... yes
Let's say I'm writing something that depends on external programs, like svn
. How do I check for their existence automatically, so I can print a helpful error message when they're absent? Iterating through PATH
is possible, but hardly elegant and efficient. Are there cleaner solutions?
I've seen this behavior in a bootstrapping script, though I can't remember where. It looked a little like this:
checking for gcc... yes
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您使用的是 bash,则可以使用内置的
type
:如果您想在脚本中使用它:
If you are using bash, you can use the
type
builtin:If you want to use it in a script:
尝试实际调用它。
使用
-V
或任何其他使程序报告其版本的选项来调用它是最有意义的;大多数时候你希望程序至少是这样那样的版本。如果您的程序是 shell 脚本,那么
which
也是您的朋友。Try to actually call it.
It makes most sense to call it with
-V
or whatever else option that makes the program report its version; most of the time you want the program to be at least such-and-such version.If your program is a shell script,
which
is your friend, too.