Declaring required commands in bash scripts
It's funny how easy it is to overlook an obvious solution to a trivial problem and keep doing things the slow way for years at a time.
While writing a short bash script today, it occurred to me that I've been handling requirements poorly for years. I've previously used long chains of if !$(which COMMAND) &>/dev/null
to declare and enforce requirements but it never occurred to me to wrap it in a simple function. This is what popped out of my head today:
#!/bin/bash
# Declare requirements in bash scripts
set -e
function requires() {
if ! command -v $1 &>/dev/null; then
echo "Requires $1"
exit 1
fi
}
requires "jq"
requires "curl"
# etc.
# ... rest of script
This makes it easy to declare simple command requirements without repeating the basic if not found then fail
logic over and over. In hindsight it should have been obvious to wrap this stuff in a function years ago, but at least I've caught up now.
The requires function can of course be placed in a common file for inclusion into multiple scripts. I've shown it inline for simplicity.
This snippet also available as a Gist.