Skip to content
GreenSnippets

Check that required commands are installed

Fail early with a helpful message when a script depends on tools that are missing.

Bash
require_commands() {
  local missing=()
  local cmd
  for cmd in "$@"; do
    command -v "$cmd" >/dev/null 2>&1 || missing+=("$cmd")
  done
  if (( ${#missing[@]} > 0 )); then
    echo "Missing required commands: ${missing[*]}" >&2
    return 1
  fi
}

Example / expected output

Output
require_commands curl jq git || exit 1

How it works

Scripts that die halfway because jq is missing leave things half-done. command -v is the portable, builtin way to test for a command (unlike which). Collect all missing tools and report them together so the user installs everything in one go.

This snippet has been reviewed but was not executed by an automated test. Test it in your own environment before relying on it.