Course contentsShow
← Linux
Lesson 130 of 1,8192. Deep Dive into Bash ScriptingFree lesson

Dependency Check Automation

Verify the presence and versions of system tools before executing logic.

In this lesson, you will learn how to make your Bash scripts "self-aware" by verifying that required system tools are present and meet specific version requirements before your main logic runs.

Why Validate Dependencies?

Have you ever run a script only to have it crash halfway through because a command like jq or git wasn't installed? Instead of letting the script fail with cryptic errors later, we can implement Dependency Check Automation. This ensures your script provides a helpful error message to the user immediately, explaining exactly what is missing.

The "Command Existence" Pattern

To check if a command exists, the most portable and efficient method is using the command -v utility. Unlike which, which can sometimes be unreliable or behave differently across shells, command -v is a shell builtin.

#!/bin/bash
set -euo pipefail

# Define our required tool
REQUIRED_TOOL="git"

if ! command -v "$REQUIRED_TOOL" &> /dev/null; then
    echo "Error: '$REQUIRED_TOOL' is not installed. Please install it to continue."
    exit 1
fi

Validating Version Requirements

Sometimes, it is not enough to just have the tool; you need a specific version to ensure your script’s logic works as expected. You can capture the version output and compare it using Bash's arithmetic expressions or string comparison.

# Check version (e.g., git version 2.34.1)
CURRENT_VERSION=$(git --version | awk '{print $3}' | cut -d. -f1)

if [ "$CURRENT_VERSION" -lt 2 ]; then
    echo "Error: This script requires git version 2.x or higher."
    exit 1
fi

Best Practice: The "Check Loop"

For scripts with multiple dependencies, you can iterate through a list stored in an array. This keeps your script clean and makes it easy to add new requirements later without duplicating your error-handling logic.

DEPENDENCIES=("git" "curl" "jq")

for cmd in "${DEPENDENCIES[@]}"; do
    if ! command -v "$cmd" &> /dev/null; then
        echo "Missing dependency: $cmd"
        exit 1
    fi
done

By verifying the environment before execution, you transform a fragile script into a robust professional tool that communicates clearly with the user.

Key Takeaway: Always validate your script's external requirements at the very beginning to prevent undefined behavior and provide clear feedback when system prerequisites are not met.