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

后端 未结 30 2030
有刺的猬
有刺的猬 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条回答
  •  猫巷女王i
    2020-11-21 08:04

    To mimic Bash's type -P cmd, we can use the POSIX compliant env -i type cmd 1>/dev/null 2>&1.

    man env
    # "The option '-i' causes env to completely ignore the environment it inherits."
    # In other words, there are no aliases or functions to be looked up by the type command.
    
    ls() { echo 'Hello, world!'; }
    
    ls
    type ls
    env -i type ls
    
    cmd=ls
    cmd=lsx
    env -i type $cmd 1>/dev/null 2>&1 || { echo "$cmd not found"; exit 1; }
    

提交回复
热议问题