BASH

Parsing Command-Line Arguments in Bash Scripts

Master parsing command-line arguments in bash scripts using `getopts` for robust and flexible script execution, handling various options and parameters efficiently.

#!/bin/bash

# Default values
VERBOSE=false
OUTPUT_FILE="output.txt"
MODE="default"

# Function to display usage information
usage() {
    echo "Usage: $0 [-v] [-o <file>] [-m <mode>] <argument1> [argument2...]"
    echo "  -v        Enable verbose output"
    echo "  -o <file> Specify output file (default: $OUTPUT_FILE)"
    echo "  -m <mode> Set mode (e.g., 'test', 'production')"
    echo "  <argument> Required positional arguments"
    exit 1
}

# Parse options using getopts
while getopts "vo:m:" opt; do
    case $opt in
        v)
            VERBOSE=true
            ;;
        o)
            OUTPUT_FILE="$OPTARG"
            ;;
        m)
            MODE="$OPTARG"
            ;;
        \?)
            echo "Invalid option: -$OPTARG" >&2
            usage
            ;;
        :)
            echo "Option -$OPTARG requires an argument." >&2
            usage
            ;;
    esac
done

# Shift off the options so that "$@" refers to the positional arguments
shift $((OPTIND-1))

# Check for required positional arguments
if [ "$#" -eq 0 ]; then
    echo "Error: At least one positional argument is required." >&2
    usage
fi

# Display parsed values
echo "--- Script Configuration ---"
echo "Verbose: $VERBOSE"
echo "Output File: $OUTPUT_FILE"
echo "Mode: $MODE"
echo "Positional Arguments:"
for arg in "$@"; do
    echo "- $arg"
done
echo "----------------------------"

# Example: Perform some action based on arguments
if "$VERBOSE"; then
    echo "Running in verbose mode..."
fi

echo "Script finished."
How it works: This script demonstrates robust command-line argument parsing using `getopts`. It handles optional flags (e.g., `-v` for verbose), options requiring values (e.g., `-o <file>`), and positional arguments. The `usage` function provides help, and `shift $((OPTIND-1))` correctly separates processed options from regular positional arguments, making the script more flexible and user-friendly.

Need help integrating this into your project?

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

Hire DigitalCodeLabs