如何在bash中检查命令的存在?

时间:2015-06-29 05:06:57

标签: bash shell

我正在尝试编写一个配置脚本,只有当它们不存在时才需要安装几个包,所以我尝试了以下方法,但是我在屏幕上看到“命令未找到”的错误

我试过了:

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

    function test {
    "$@"
    local status=$?
    if [ $status -ne 0 ]; then
        #install this package
    fi
    return $status
}

test command1
test command2

1 个答案:

答案 0 :(得分:1)

您还希望将stderr重定向到/dev/null(不只是stdout)。

为此,您可以使用将stderr加入stdout的2>&1重定向,然后将其重定向到/dev/null

以下内容应该有效:

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

请注意,不要这样做,您也可以这样做:

if ! type "$foobar_command_name" >/dev/null 2>/dev/null; then
  # install foobar here
fi
相关问题