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

后端 未结 30 2669
有刺的猬
有刺的猬 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 07:51

    The following is a portable way to check whether a command exists in $PATH and is executable:

    [ -x "$(command -v foo)" ]
    

    Example:

    if ! [ -x "$(command -v git)" ]; then
      echo 'Error: git is not installed.' >&2
      exit 1
    fi
    

    The executable check is needed because bash returns a non-executable file if no executable file with that name is found in $PATH.

    Also note that if a non-executable file with the same name as the executable exists earlier in $PATH, dash returns the former, even though the latter would be executed. This is a bug and is in violation of the POSIX standard. [Bug report] [Standard]

    In addition, this will fail if the command you are looking for has been defined as an alias.

提交回复
热议问题