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

后端 未结 30 2887
有刺的猬
有刺的猬 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:04

    I agree with lhunath to discourage use of which, and his solution is perfectly valid for Bash users. However, to be more portable, command -v shall be used instead:

    $ command -v foo >/dev/null 2>&1 || { echo "I require foo but it's not installed.  Aborting." >&2; exit 1; }
    

    Command command is POSIX compliant. See here for its specification: command - execute a simple command

    Note: type is POSIX compliant, but type -P is not.

提交回复
热议问题