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

Command-Line Argument Parsing Patterns

Implement flexible flags and long options without external dependencies.

In this lesson, you will learn how to build a professional-grade command-line interface for your scripts using native Bash case statements and loops to handle flags and long options.

The "Loop-and-Shift" Pattern

When you run a script like ./deploy.sh --environment production -v, Bash stores those inputs in a list called positional parameters ($1, $2, etc.). To handle these flexibly, we use a while loop combined with the shift command.

The shift command is the secret sauce: it discards the first argument and moves every other argument one position to the left. This allows us to process the "next" argument in each iteration of the loop.

Implementing the Parser

Here is a pattern for handling both short flags (like -v) and long options (like --environment) without needing external tools like getopt:

#!/usr/bin/env bash

# Default values
VERBOSE=false
ENV="development"

while [[ $# -gt 0 ]]; do
  case "$1" in
    -v|--verbose)
      VERBOSE=true
      shift # Move to next argument
      ;;
    -e|--environment)
      ENV="$2" # Capture the value following the flag
      shift 2  # Skip both the flag and its value
      ;;
    *)
      echo "Unknown option: $1"
      exit 1
      ;;
  esac
done

echo "Running in $ENV mode (Verbose: $VERBOSE)"

Why this approach?

  1. Flexibility: By checking the pattern *), you can gracefully handle invalid inputs or provide help menus.
  2. Order Independence: Because we loop through all arguments, the user can provide ./script.sh -v -e production or ./script.sh -e production -v interchangeably.
  3. No Dependencies: This relies purely on Bash built-ins, ensuring your script remains portable and lightweight across any system, regardless of installed packages.

By checking the remainder of the loop ($# -gt 0), we ensure we consume every argument provided by the user until the list is empty. If an option requires a parameter (like --environment), we simply grab the next positional parameter ($2) and shift 2 to move past both the flag and its value.

Key Takeaway: Use a while loop with shift to consume arguments one by one, allowing your scripts to handle complex, order-independent inputs natively.