Today, I will illustrate a simple way to check for specific command inside a shell script, which is quite simple as it uses only shell built-in command
utility.
Shell function to check for a 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 available" fi done
Sample output.
bash - command is available [bash is a tracked alias for /bin/bash] bashdb - command is not available mc - command is available [mc is a tracked alias for /usr/bin/mc] openssl-dev - command is 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 to 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.