BASH

Check if Command Exists and Install if Missing

Write a Bash script to verify the presence of a required command (e.g., `jq`, `curl`) and provide instructions or attempt installation using common package managers like `apt`, `yum`, or `brew`.

#!/bin/bash

# Function to check if a command exists
command_exists () {
  command -v "$1" >/dev/null 2>&1
}

# List of commands to check
REQUIRED_COMMANDS=("jq" "curl" "git") # Add/remove commands as needed

# Check for each command
for cmd in "${REQUIRED_COMMANDS[@]}"; do
  if ! command_exists "$cmd"; then
    echo "Error: Required command '$cmd' is not installed." >&2
    echo "Attempting to install '$cmd'..."

    # Attempt installation based on OS/package manager
    if command_exists "apt-get"; then
      sudo apt-get update && sudo apt-get install -y "$cmd"
    elif command_exists "yum"; then
      sudo yum install -y "$cmd"
    elif command_exists "brew"; then
      brew install "$cmd"
    else
      echo "Could not find a suitable package manager to install '$cmd'." >&2
      echo "Please install '$cmd' manually and try again." >&2
      exit 1
    fi

    # Verify installation
    if ! command_exists "$cmd"; then
      echo "Installation of '$cmd' failed. Please install it manually." >&2
      exit 1
    else
      echo "'$cmd' installed successfully."
    fi
  else
    echo "Command '$cmd' is already installed."
  fi
done

echo "All required commands are available."
# Your script logic continues here...
How it works: This script checks for the presence of essential system commands before executing further logic. It defines a `command_exists` function that uses `command -v` to check if a command is in the system's PATH. It then iterates through a list of `REQUIRED_COMMANDS`. If a command is missing, it attempts to install it using common package managers (`apt-get` for Debian/Ubuntu, `yum` for RedHat/CentOS, `brew` for macOS) based on which package manager is available on the system. If installation fails or no suitable package manager is found, the script exits with an error, ensuring prerequisites are met.

Need help integrating this into your project?

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

Hire DigitalCodeLabs