BASH

Implement Robust Command-Line Argument Parsing

Enhance your Bash scripts by implementing robust command-line argument parsing with 'getopts', making them flexible, user-friendly, and error-resistant.

#!/bin/bash

# Script to demonstrate robust argument parsing

PORT=""
HOST="localhost"
VERBOSE=0

usage() {
  echo "Usage: $0 [-p <port>] [-h <host>] [-v] <action>"
  echo "  -p <port>  : Specify port number (e.g., 8080)"
  echo "  -h <host>  : Specify host (default: localhost)"
  echo "  -v         : Enable verbose output"
  echo "  <action>   : Required action (e.g., 'start', 'stop', 'status')"
  exit 1
}

# Parse options using getopts. The leading colon in ":p:h:v" enables silent error reporting for invalid options and missing arguments.
while getopts ":p:h:v" opt; do
  case $opt in
    p)
      PORT="$OPTARG"
      # Basic validation: ensure port is a number
      if ! [[ "$PORT" =~ ^[0-9]+$ ]]; then
        echo "Error: Port must be a number." >&2
        usage
      fi
      ;;
    h)
      HOST="$OPTARG"
      ;;
    v)
      VERBOSE=1
      ;;
    \?)
      echo "Invalid option: -$OPTARG" >&2
      usage
      ;;
    :)
      echo "Option -$OPTARG requires an argument." >&2
      usage
      ;;
  esac
done

# Shift off the options, leaving only positional arguments
shift $((OPTIND-1))

# Get the required action (positional argument)
ACTION="$1"

if [ -z "$ACTION" ]; then
  echo "Error: Action is required." >&2
  usage
fi

# --- Script Logic based on parsed arguments ---

if [ "$VERBOSE" -eq 1 ]; then
  echo "Verbose mode enabled."
  echo "Port: $PORT"
  echo "Host: $HOST"
  echo "Action: $ACTION"
fi

case "$ACTION" in
  start)
    echo "Starting service on $HOST${PORT:+:$PORT}..." # Only append port if it's set
    # Add your service start logic here
    ;;
  stop)
    echo "Stopping service on $HOST${PORT:+:$PORT}..."
    # Add your service stop logic here
    ;;
  status)
    echo "Checking status of service on $HOST${PORT:+:$PORT}..."
    # Add your service status check logic here
    ;;
  *)
    echo "Invalid action: $ACTION" >&2
    usage
    ;;
esac

echo "Script finished."
How it works: This script demonstrates robust parsing of command-line options (e.g., `-p` for port, `-h` for host, `-v` for verbose) and positional arguments (e.g., `start`, `stop`) using the built-in `getopts` command. It includes a `usage` function for displaying help, basic validation for arguments, and handles invalid options or missing arguments gracefully, making your Bash scripts more powerful and user-friendly for web development automation.

Need help integrating this into your project?

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

Hire DigitalCodeLabs