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

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

    It depends on whether you want to know whether it exists in one of the directories in the $PATH variable or whether you know the absolute location of it. If you want to know if it is in the $PATH variable, use

    if which programname >/dev/null; then
        echo exists
    else
        echo does not exist
    fi
    

    otherwise use

    if [ -x /path/to/programname ]; then
        echo exists
    else
        echo does not exist
    fi
    

    The redirection to /dev/null/ in the first example suppresses the output of the which program.

提交回复
热议问题