BASH

Building a Bash Utility Function Library

Enhance your bash scripts by creating a library of reusable functions for common tasks like logging, confirmation prompts, and checking command availability.

#!/bin/bash

# --- Bash Utility Function Library ---

# Function for logging messages with different levels
log_message() {
  local level="$1"
  shift
  local message="$@"
  local timestamp=$(date +"%Y-%m-%d %H:%M:%S")

  case "$level" in
    INFO)
      echo "[INFO] $timestamp: $message"
      ;;
    WARN)
      echo "[WARN] $timestamp: $message" >&2
      ;;
    ERROR)
      echo "[ERROR] $timestamp: $message" >&2
      ;;
    DEBUG)
      # Only print debug messages if DEBUG_MODE is enabled
      if [ "$DEBUG_MODE" = true ]; then
        echo "[DEBUG] $timestamp: $message"
      fi
      ;;
    *)
      echo "[$level] $timestamp: $message"
      ;;
  esac
}

# Function to confirm an action with the user
confirm_action() {
  local prompt="$1"
  while true; do
    read -p "$prompt (y/n): " choice
    case "$choice" in
      y|Y ) return 0; ; # User confirmed
      n|N ) return 1; ; # User denied
      * ) echo "Invalid input. Please enter y or n." ;;
    esac
  done
}

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

# Function to get script's absolute path
get_script_dir() {
  local SCRIPT_SOURCE="${BASH_SOURCE[0]}"
  local SCRIPT_DIR="$( dirname "$SCRIPT_SOURCE" )"
  echo "$(cd "$SCRIPT_DIR" && pwd)"
}

# --- End Bash Utility Function Library ---

# --- Example Usage ---

DEBUG_MODE=true # Set to true to see DEBUG messages
SCRIPT_DIRECTORY=$(get_script_dir)

log_message INFO "Script started from: $SCRIPT_DIRECTORY"
log_message DEBUG "Debug mode is enabled."

if command_exists "git"; then
  log_message INFO "Git command found."
else
  log_message WARN "Git command not found. Please install Git."
fi

if confirm_action "Do you want to proceed with a dummy operation?"; then
  log_message INFO "User confirmed. Performing dummy operation..."
  sleep 2 # Simulate work
  log_message INFO "Dummy operation complete."
else
  log_message ERROR "User cancelled. Aborting script."
  exit 1
fi

log_message INFO "Script finished successfully."
How it works: This snippet demonstrates how to create a reusable library of utility functions in Bash, significantly improving script organization, readability, and maintainability. It includes functions for structured logging (INFO, WARN, ERROR, DEBUG with colored output), prompting the user for confirmation, checking for the existence of external commands, and determining the script's absolute directory. These functions can be sourced into any Bash script to provide common functionalities, reducing code duplication and making scripts more robust and user-friendly for complex web development workflows.

Need help integrating this into your project?

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

Hire DigitalCodeLabs