How to check for command inside shell script

Today, I will illustrate a simple way to check for specifc command inside shell script, which is quite simple as it uses only shell built-in command utility.

Shell function to check for specific command.

# check for specific command
# Return values:
#  0 - command is available
#  1 - command is not available
check_for_command(){
  command -v "$1" 1>/dev/null 2>&-
}

Regular shell script to illustrate the usage.

#!/bin/sh
# check for specific command
# Return values:
#  0 - command is available
#  1 - command is not available
check_for_command(){
  command -v "$1" 1>/dev/null 2>&-
}

# example
commands="bash bashdb mc openssl-dev type"

for command in $commands; do
  if check_for_command "$command"; then
    printf "%-20s - %s\n" "$command" "command is available [$(type $command)]"
  else
    printf "%-20s - %s\n" "$command" "command is not not available"
  fi
done

Sample output.

bash                 - command is available [bash is a tracked alias for /bin/bash]
bashdb               - command is not not available
mc                   - command is available [mc is a tracked alias for /usr/bin/mc]
openssl-dev          - command is not not available
type                 - command is available [type is a shell builtin]

Additional notes

I cannot use simple &>/dev/null redirection as dash command interpreter does not support it, so I need take advantage of the longer 1>/dev/null 2>&1 version to get rid of the whole (standard and error) output inside shell functions.

References

Read check if a program exists from a Bash script to find other solutions.

Milosz Galazka's Picture

About Milosz Galazka

Milosz is a system administrator working for a successful Polish company and a long time supporter of Free Software Foundation and Debian operating system.

Gdansk, Poland https://sleeplessbeastie.eu