BASH

Parse Command Line Options with `getopts`

A robust bash script demonstrating how to parse command-line arguments and options using `getopts` for flexible script execution.

#!/bin/bash

# Default values
VERBOSE=0
ENVIRONMENT="development"
CONFIG_PATH="/etc/app/config.conf"

# Usage function
usage() {
  echo "Usage: $0 [-v] [-e <environment>] [-c <config_path>]"
  echo "  -v: Enable verbose output."
  echo "  -e: Specify environment (e.g., development, staging, production). Default: development."
  echo "  -c: Path to the configuration file. Default: /etc/app/config.conf."
  exit 1
}

# Parse options
while getopts "ve:c:" opt; do
  case "${opt}" in
    v)
      VERBOSE=1
      ;;
    e)
      ENVIRONMENT=${OPTARG}
      ;;
    c)
      CONFIG_PATH=${OPTARG}
      ;;
    *)
      usage
      ;;
  esac
done

# Shift arguments so that remaining non-option arguments can be accessed
shift $((OPTIND-1))

# Example: Process remaining arguments if any
if [ -n "$1" ]; then
  echo "Remaining argument: $1"
fi

# Output parsed values
echo "--- Script Configuration ---"
echo "Verbose: $VERBOSE"
echo "Environment: $ENVIRONMENT"
echo "Config Path: $CONFIG_PATH"
echo "----------------------------"

# Your script logic would go here, using the parsed variables.
if [ "$VERBOSE" -eq 1 ]; then
  echo "Verbose mode enabled for detailed operations."
fi
# Example: Perform actions based on environment
# if [ "$ENVIRONMENT" == "production" ]; then
#   echo "Running in production mode."
# fi
How it works: This script demonstrates how to parse command-line options using `getopts`, a built-in bash utility for handling short options. It defines default values for variables like `VERBOSE`, `ENVIRONMENT`, and `CONFIG_PATH`. The `while getopts` loop processes the options (`-v`, `-e`, `-c`) and assigns their values (or sets flags) accordingly. The `shift` command then removes the processed options, leaving any remaining positional arguments. This approach makes scripts more flexible and user-friendly by allowing configurable behavior directly from the command line.

Need help integrating this into your project?

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

Hire DigitalCodeLabs