← Back to all snippets
BASH

Robust Command-Line Argument Parsing with getopts

Learn how to parse command-line options and arguments robustly in Bash scripts using the built-in `getopts` command for better script usability and flexibility, handling flags and values.

#!/bin/bash

# Default values
VERBOSE=0
OUTPUT_FILE=""

# Parse options
while getopts "vo:" opt; do
  case $opt in
    v)
      VERBOSE=1
      ;;
    o)
      OUTPUT_FILE="$OPTARG"
      ;;
    \?)
      echo "Usage: $0 [-v] [-o output_file] <arguments...>" >&2
      exit 1
      ;;
  esac
done

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

# Now, positional arguments can be accessed via $1, $2, etc.
INPUT_ARG="$1"

if [ -z "$INPUT_ARG" ]; then
  echo "Error: An input argument is required." >&2
  echo "Usage: $0 [-v] [-o output_file] <input_argument>" >&2
  exit 1
fi

if [ "$VERBOSE" -eq 1 ]; then
  echo "Verbose mode enabled." 
  echo "Output file: ${OUTPUT_FILE:-"(not specified)"}"
  echo "Input argument: $INPUT_ARG"
fi

if [ -n "$OUTPUT_FILE" ]; then
  echo "Processing $INPUT_ARG..." > "$OUTPUT_FILE"
  echo "Result for $INPUT_ARG saved to $OUTPUT_FILE"
else
  echo "Processing $INPUT_ARG..." 
  echo "Result for $INPUT_ARG displayed on stdout."
fi

# Example usage: ./myscript.sh -v -o results.txt "hello world"
How it works: This snippet demonstrates how to parse command-line arguments using `getopts`, a Bash built-in for handling short options. The `while getopts` loop processes flags like `-v` (verbose) and options with values like `-o output_file`. The `OPTARG` variable holds the value for options like `-o`. After parsing options, `shift "$(($OPTIND - 1))"` moves past the processed options, allowing you to access remaining positional arguments using `$1`, `$2`, etc. This provides a structured and user-friendly way to control script behavior.

Need help integrating this into your project?

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

Hire DigitalCodeLabs