BASH

Parse Command Line Arguments in Bash with getopts

Discover how to robustly parse command-line options and arguments in bash scripts using `getopts`, supporting both short and long options for flexible script execution.

#!/bin/bash

# --- Configuration & Defaults ---
FILE_PATH="default.txt"
VERBOSE=false
DRY_RUN=false

# --- Help Function ---
function show_help {
    echo "Usage: $(basename "$0") [-f <file>] [-v] [-d] [--help] [arg1 arg2 ...]"
    echo "  -f <file>   Specify a file path (default: $FILE_PATH)"
    echo "  -v          Enable verbose output"
    echo "  -d          Perform a dry run (no actual changes)"
    echo "  --help      Display this help message"
    echo "  [arg...]    Positional arguments that follow options"
    exit 0
}

# --- Parse Options with getopts ---
# 'f:' means -f requires an argument
# 'v' and 'd' are flags without arguments

while getopts "f:vdh-" opt; do
    case "$opt" in
        f) FILE_PATH="$OPTARG";; # Argument for -f is in $OPTARG
        v) VERBOSE=true;;
        d) DRY_RUN=true;;
        h) show_help;;
        -) # Handle long options (e.g., --help)
            case "$OPTARG" in
                help) show_help;;
                *) echo "Invalid option: --$OPTARG" >&2; exit 1;;
            esac
            ;;
        \?) # Invalid short option
            echo "Invalid option: -$OPTARG" >&2
            show_help
            exit 1
            ;;
    esac
done

# Shift off the options from the arguments, so remaining are positional
shift $((OPTIND - 1))

# --- Main Script Logic ---

echo "Script started with the following parameters:"
echo "  File Path: $FILE_PATH"
echo "  Verbose Mode: $VERBOSE"
echo "  Dry Run Mode: $DRY_RUN"

if [ "$#" -gt 0 ]; then
    echo "  Positional Arguments: $@"
else
    echo "  No positional arguments provided."
fi

if [ "$DRY_RUN" = true ]; then
    echo "(Dry run mode: No actual operations will be performed.)"
fi

# Example of using parameters
if [ "$VERBOSE" = true ]; then
    echo "Verbose output enabled: Processing file $FILE_PATH..."
fi

if [ -f "$FILE_PATH" ]; then
    echo "File '$FILE_PATH' exists. Content (first line):"
    head -n 1 "$FILE_PATH"
else
    echo "File '$FILE_PATH' does not exist."
fi

echo "Script finished."
How it works: This script demonstrates a robust way to parse command-line arguments in bash using `getopts`. It allows for defining both short options (e.g., `-f`, `-v`) and basic long options (e.g., `--help`). The script sets default values, then overrides them based on user input. It also correctly handles positional arguments that follow the options. This method makes your bash scripts more user-friendly and flexible, providing clear usage instructions via a help function.

Need help integrating this into your project?

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

Hire DigitalCodeLabs