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

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

    The which command might be useful. man which

    It returns 0 if the executable is found and returns 1 if it's not found or not executable:

    NAME
    
           which - locate a command
    
    SYNOPSIS
    
           which [-a] filename ...
    
    DESCRIPTION
    
           which returns the pathnames of the files which would
           be executed in the current environment, had its
           arguments been given as commands in a strictly
           POSIX-conformant shell. It does this by searching
           the PATH for executable files matching the names
           of the arguments.
    
    OPTIONS
    
           -a     print all matching pathnames of each argument
    
    EXIT STATUS
    
           0      if all specified commands are 
                  found and executable
    
           1      if one or more specified commands is nonexistent
                  or not executable
    
           2      if an invalid option is specified
    

    The nice thing about which is that it figures out if the executable is available in the environment that which is run in - it saves a few problems...

提交回复
热议问题