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

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

    If there isn't any external type command available (as taken for granted here), we can use POSIX compliant env -i sh -c 'type cmd 1>/dev/null 2>&1':

    # Portable version of Bash's type -P cmd (without output on stdout)
    typep() {
       command -p env -i PATH="$PATH" sh -c '
          export LC_ALL=C LANG=C
          cmd="$1"
          cmd="`type "$cmd" 2>/dev/null || { echo "error: command $cmd not found; exiting ..." 1>&2; exit 1; }`"
          [ $? != 0 ] && exit 1
          case "$cmd" in
            *\ /*) exit 0;;
                *) printf "%s\n" "error: $cmd" 1>&2; exit 1;;
          esac
       ' _ "$1" || exit 1
    }
    
    # Get your standard $PATH value
    #PATH="$(command -p getconf PATH)"
    typep ls
    typep builtin
    typep ls-temp
    

    At least on Mac OS X v10.6.8 (Snow Leopard) using Bash 4.2.24(2) command -v ls does not match a moved /bin/ls-temp.

提交回复
热议问题