BASH
Verifying Essential System Commands for Bash Scripts
Ensure your Bash scripts run smoothly by programmatically checking for the presence of necessary system commands (like `curl` or `git`) and providing user-friendly installation instructions if missing.
#!/bin/bash
REQUIRED_COMMANDS=("curl" "git" "jq")
MISSING_COMMANDS=()
echo "Verifying essential system commands..."
for cmd in "${REQUIRED_COMMANDS[@]}"; do
if ! command -v "$cmd" &> /dev/null; then
MISSING_COMMANDS+=("$cmd")
fi
done
if [[ ${#MISSING_COMMANDS[@]} -gt 0 ]]; then
echo "Error: The following essential commands are missing:"
for missing_cmd in "${MISSING_COMMANDS[@]}"; do
echo "- $missing_cmd"
done
echo "
Please install them to proceed."
echo "Example for Debian/Ubuntu: sudo apt-get update && sudo apt-get install ${MISSING_COMMANDS[*]}"
echo "Example for macOS (with Homebrew): brew install ${MISSING_COMMANDS[*]}"
exit 1
else
echo "All required commands are present."
fi
echo "Script can now proceed with its tasks."
How it works: This script verifies the existence of a list of required system commands (e.g., `curl`, `git`, `jq`) before proceeding. It iterates through an array of command names and uses `command -v` to check if each command is found in the system's PATH. If any command is missing, it collects them, prints an error message with suggested installation commands, and exits with an error status, ensuring the script doesn't attempt to use non-existent tools.