使用 bash 检查程序是否存在的首选方法是什么

What is the preferred way to check whether a program exists with bash

我正在编写一个脚本,它将 运行 用不同语言编写的程序的多个版本,因此它应该能够检测系统是否可以首先 运行 一个文件。我发现 this question 有点用处,但我想知道是否可以改进我现有的代码。

我使用以下方法检查程序是否存在。

if type "$PROGRAM" >/dev/null 2>&1; then
  # OK
fi

我在争论这个问题是否应该进入代码审查,但我决定 post 在这里,因为它只有 2 行代码。

我在 bash 中使用这个:

# Convenience method to check if a command exists or not.
function command_exists {
  hash "" &> /dev/null
}

这给了我 command_exists:

if command_exists "vim"; then
  echo "and there was great rejoicing!"
fi

或一次性:

command_exists "vim" && echo "and there was great rejoicing!"

function die {
  echo ""
  exit 1
}
command_exists "vim" || die "Vim needs to be installed"