← Back to all snippets
BASH

Robust Command Line Argument Parsing

Master parsing command-line options and arguments in bash scripts using `getopts` for creating flexible and user-friendly utilities with short flags.

#!/bin/bash

# Default values
VERBOSE=0
OUTPUT_FILE=""
INPUT_PATH=""

usage() {
    echo "Usage: $0 [-v] [-o <output_file>] <input_path>"
    echo "  -v: Verbose mode"
    echo "  -o <output_file>: Specify an output file"
    echo "  <input_path>: Required input file or directory path"
    exit 1
}

# Parse options
while getopts "vo:" opt; do
    case $opt in
        v) VERBOSE=1 ;;
        o) OUTPUT_FILE="$OPTARG" ;;
        \?) usage ;; # Handle invalid options
    esac
done

# Shift parsed options so that remaining arguments are positional
shift $((OPTIND - 1))

# Check for required positional argument
if [ -z "$1" ]; then
    echo "Error: Input path is required."
    usage
fi
INPUT_PATH="$1"

# --- Script Logic Starts Here ---
echo "Processing input path: $INPUT_PATH"

if [ -n "$OUTPUT_FILE" ]; then
    echo "Output will be redirected to: $OUTPUT_FILE"
    # Example: command > "$OUTPUT_FILE"
fi

if [ "$VERBOSE" -eq 1 ]; then
    echo "Verbose mode is enabled."
    echo "Additional debug information here..."
fi

# Example: Perform some operation with INPUT_PATH
# ls -l "$INPUT_PATH"
How it works: This script demonstrates robust command-line argument parsing using `getopts`. It allows for defining short options like `-v` for verbose mode and `-o <output_file>` to specify an output file. A `usage` function provides help, and `shift $((OPTIND - 1))` cleanly separates options from positional arguments. The script checks for a required positional argument (`INPUT_PATH`) and then uses the parsed values in its main logic, making scripts more versatile.

Need help integrating this into your project?

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

Hire DigitalCodeLabs