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

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

    If you check for program existence, you are probably going to run it later anyway. Why not try to run it in the first place?

    if foo --version >/dev/null 2>&1; then
        echo Found
    else
        echo Not found
    fi
    

    It's a more trustworthy check that the program runs than merely looking at PATH directories and file permissions.

    Plus you can get some useful result from your program, such as its version.

    Of course the drawbacks are that some programs can be heavy to start and some don't have a --version option to immediately (and successfully) exit.

提交回复
热议问题