Checking requirements in BASH
After writing many scripts, I've evolved a 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=("$@")
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.