← Back to all snippets
BASH

Check and Install Command If Missing

Essential Bash snippet for web developers to ensure required command-line tools like 'jq' or 'git' are installed, prompting installation if absent.

#!/bin/bash

check_and_install() {
  local cmd="$1"
  if ! command -v "$cmd" &> /dev/null; then
    echo "Command '$cmd' not found. Attempting to install..."
    if [[ "$OSTYPE" == "linux-gnu"* ]]; then
      # Assume Debian/Ubuntu for apt, adjust for others like yum/dnf
      sudo apt update && sudo apt install -y "$cmd"
    elif [[ "$OSTYPE" == "darwin"* ]]; then
      # macOS with Homebrew
      brew install "$cmd"
    else
      echo "Unsupported OS. Please install '$cmd' manually."
      exit 1
    fi
    if ! command -v "$cmd" &> /dev/null; then
      echo "Failed to install '$cmd'. Exiting."
      exit 1
    fi
    echo "'$cmd' installed successfully."
  else
    echo "'$cmd' is already installed."
  fi
}

# Example usage:
# check_and_install "jq"
# check_and_install "node"
# check_and_install "yarn"
How it works: This script defines a function `check_and_install` that takes a command name as an argument. It checks if the command exists using `command -v`. If not found, it attempts to install it based on the operating system (Linux with `apt` or macOS with `brew`). This is highly useful for ensuring developer environments have necessary command-line tools like `jq`, Node.js, or `yarn` installed before running other scripts or build processes.

Need help integrating this into your project?

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

Hire DigitalCodeLabs