Checking requirements in Bash

Checking requirements in Bash

After writing many scripts, I’ve evolved a concise pattern for checking for Bash script requirements.

readonly REQUIREMENTS=("git" "docker")

# Check for installed cli tools
# @param array names of required tools
function requires() {
   local arr=("[email protected]")
   for i in "${arr[@]}"; do
      if ! hash "$i" &>/dev/null; then
        echo "Requires $i"
        exit 1 
      fi
   done
}

requires "${REQUIREMENTS[@]}"

The pattern consists of setting an array of required command names, looping over them, and checking if they are installed. Compared to one-off checks throughout a script, this pattern unifies requirements in one spot.

Published
About WorkNow