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

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

    I'd say there isn't any portable and 100% reliable way due to dangling aliases. For example:

    alias john='ls --color'
    alias paul='george -F'
    alias george='ls -h'
    alias ringo=/
    

    Of course, only the last one is problematic (no offence to Ringo!). But all of them are valid aliases from the point of view of command -v.

    In order to reject dangling ones like ringo, we have to parse the output of the shell built-in alias command and recurse into them (command -v isn't a superior to alias here.) There isn't any portable solution for it, and even a Bash-specific solution is rather tedious.

    Note that a solution like this will unconditionally reject alias ls='ls -F':

    test() { command -v $1 | grep -qv alias }
    

提交回复
热议问题