如何检查命令是否存在于 shell 脚本中? [英] How can I check if a command exists in a shell script?

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

问题描述

我正在编写我的第一个 shell 脚本.在我的脚本中,我想检查某个命令是否存在,如果不存在,请安装可执行文件.我将如何检查此命令是否存在?

I am writing my first shell script. In my script I would like to check if a certain command exists, and if not, install the executable. How would I check if this command exists?

if # Check that foobar command doesnt exist
then
    # Now install foobar
fi

推荐答案

通常,这取决于您的 shell,但如果您使用 bash、zsh、ksh 或 sh(由 dash 提供),以下内容应该有效:

In general, that depends on your shell, but if you use bash, zsh, ksh or sh (as provided by dash), the following should work:

if ! type "$foobar_command_name" > /dev/null; then
  # install foobar here
fi

对于真正的安装脚本,您可能希望确保在存在别名 foobar 的情况下 type 不会成功返回.在 bash 中,您可以执行以下操作:

For a real installation script, you'd probably want to be sure that type doesn't return successfully in the case when there is an alias foobar. In bash you could do something like this:

if ! foobar_loc="$(type -p "$foobar_command_name")" || [[ -z $foobar_loc ]]; then
  # install foobar here
fi

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

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