BASH

Check for Required Commands and Install If Missing

Ensure your bash scripts have all necessary tools by checking for required commands and guiding users to install missing packages.

#!/bin/bash

REQUIRED_COMMANDS=("git" "node" "npm" "docker")
MISSING_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 required commands are missing:"
  for missing_cmd in "${MISSING_COMMANDS[@]}"; do
    echo "- $missing_cmd"
  done
  echo ""
  echo "Please install them. For example:"
  echo "  - Debian/Ubuntu: sudo apt install <command>"
  echo "  - CentOS/RHEL: sudo yum install <command>"
  echo "  - macOS (Homebrew): brew install <command>"
  exit 1
else
  echo "All required commands are present."
fi

# Continue with script logic...
echo "Script can now proceed."
How it works: This script ensures that all necessary command-line tools (e.g., `git`, `node`, `npm`, `docker`) are available before proceeding with the main logic. It iterates through a list of `REQUIRED_COMMANDS`, using `command -v` to check for their existence. If any command is missing, it prints an informative error message listing the missing tools and provides general installation instructions for various operating systems, then exits with an error status.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs