Skip to main content

Bash function that checks to see if the given command (passed as a string argument) exists on the system. The function returns 0 (success) if the command exists, and 1 if it doesn't.

#!/usr/bin/env bash

is_command() {
    # Checks to see if the given command (passed as a string argument) exists on the system.
    # The function returns 0 (success) if the command exists, and 1 if it doesn't.
    local check_command="$1"

    command -v "${check_command}" > /dev/null 2>&1
}

#
# Example usage

if is_command php; then
    phpVer="$(php <<< "<?php echo PHP_VERSION ?>")"
    printf "PHP version: %s\\n" "${phpVer}"
else
    echo "PHP not installed"
    exit 1
fi