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

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

    In case you want to check if a program exists and is really a program, not a Bash built-in command, then command, type and hash are not appropriate for testing as they all return 0 exit status for built-in commands.

    For example, there is the time program which offers more features than the time built-in command. To check if the program exists, I would suggest using which as in the following example:

    # First check if the time program exists
    timeProg=`which time`
    if [ "$timeProg" = "" ]
    then
      echo "The time program does not exist on this system."
      exit 1
    fi
    
    # Invoke the time program
    $timeProg --quiet -o result.txt -f "%S %U + p" du -sk ~
    echo "Total CPU time: `dc -f result.txt` seconds"
    rm result.txt
    

提交回复
热议问题