How can I check if a program exists from a Bash script?

后端 未结 30 2865
有刺的猬
有刺的猬 2020-11-21 07:21

How would I validate that a program exists, in a way that will either return an error and exit, or continue with the script?

It seems like it should be easy, but it\

30条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-21 08:03

    Check for multiple dependencies and inform status to end users

    for cmd in latex pandoc; do
      printf '%-10s' "$cmd"
      if hash "$cmd" 2>/dev/null; then
        echo OK
      else
        echo missing
      fi
    done
    

    Sample output:

    latex     OK
    pandoc    missing
    

    Adjust the 10 to the maximum command length. It is not automatic, because I don't see a non-verbose POSIX way to do it: How can I align the columns of a space separated table in Bash?

    Check if some apt packages are installed with dpkg -s and install them otherwise.

    See: Check if an apt-get package is installed and then install it if it's not on Linux

    It was previously mentioned at: How can I check if a program exists from a Bash script?

提交回复
热议问题