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

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

    Late answer but this is what I ended up doing.

    I just check if the command I execute returns an error code. If it returns 0 it means program is installed. Moreover you can use this to check the output of a script. Take for instance this script.

    foo.sh

    #!/bin/bash
    echo "hello world"
    exit 1 # throw some error code
    

    Examples:

    # outputs something bad... and exits
    bash foo.sh $? -eq 0 || echo "something bad happened. not installed" ; exit 1
    
    # does NOT outputs nothing nor exits because dotnet is installed on my machine
    dotnet --version $? -eq 0 || echo "something bad happened. not installed" ; exit 1
    

    Basically all this is doing is checking the exit code of a command run. the most accepted answer on this question will return true even if the command exit code is not 0.

提交回复
热议问题