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

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

    To use hash, as @lhunath suggests, in a Bash script:

    hash foo &> /dev/null
    if [ $? -eq 1 ]; then
        echo >&2 "foo not found."
    fi
    

    This script runs hash and then checks if the exit code of the most recent command, the value stored in $?, is equal to 1. If hash doesn't find foo, the exit code will be 1. If foo is present, the exit code will be 0.

    &> /dev/null redirects standard error and standard output from hash so that it doesn't appear onscreen and echo >&2 writes the message to standard error.

提交回复
热议问题