BASH

Parsing Command Line Arguments in Bash with `getopts`

Learn to efficiently parse short command-line options and their arguments using `getopts` in Bash, making your scripts more flexible and user-friendly.

#!/bin/bash

# --- Default values ---
NAME="World"
VERBOSE=0
OUTPUT_FILE=""

# --- Usage function ---
usage() {
    echo "Usage: $0 [-n <name>] [-v] [-o <output_file>]"
    echo "  -n <name>      Specify a name (default: World)"
    echo "  -v             Enable verbose mode"
    echo "  -o <output_file> Redirect output to a file"
    exit 1
}

# --- Parse options with getopts ---
# The colon after 'n' and 'o' indicates that these options require an argument.
# The initial colon suppresses default error messages.
while getopts ":n:vo:" opt; do
    case $opt in
        n)
            NAME="$OPTARG"
            ;;
        v)
            VERBOSE=1
            ;;
        o)
            OUTPUT_FILE="$OPTARG"
            ;;
        \?) # Invalid option
            echo "Invalid option: -$OPTARG" >&2
            usage
            ;;
        :) # Missing option argument
            echo "Option -$OPTARG requires an argument." >&2
            usage
            ;;
    esac
done

# Shift remaining arguments (non-options)
shift $((OPTIND-1))

# --- Apply output redirection if specified ---
if [ -n "$OUTPUT_FILE" ]; then
    exec > "$OUTPUT_FILE"
    if [ $? -ne 0 ]; then
        echo "Error: Could not redirect output to $OUTPUT_FILE." >&2
        exit 1
    fi
fi

# --- Main script logic ---
if [ "$VERBOSE" -eq 1 ]; then
    echo "Verbose mode enabled."
    echo "Hello $NAME!"
    echo "Script arguments processed."
    if [ -n "$OUTPUT_FILE" ]; then
        echo "Output redirected to: $OUTPUT_FILE"
    fi
    if [ "$#" -gt 0 ]; then
        echo "Remaining arguments: $*"
    fi
else
    echo "Hello $NAME!"
fi

echo "Script execution complete."
How it works: This script demonstrates how to parse command-line options and their arguments using the built-in `getopts` command. It supports short options with and without arguments, handles invalid options, and gracefully reports missing arguments. The `shift $((OPTIND-1))` command is used to remove parsed options, leaving only non-option arguments for further processing. This makes scripts more versatile and easier to control from the command line.

Need help integrating this into your project?

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

Hire DigitalCodeLabs