BASH

Parse Command-Line Arguments with Getopt

Learn to robustly parse command-line arguments (short and long options) in bash scripts using `getopt`, enabling flexible configuration for web development tools.

#!/bin/bash

# Default values
VERBOSE=0
OUTPUT_FILE="output.log"
ENV="development"

# Parse command-line arguments using getopt
OPTIONS=$(getopt -o vo:e: --long verbose,output:,environment: -- "$@")

if [ $? -ne 0 ]; then
    echo "Error: Invalid arguments." >&2
    exit 1
fi

eval set -- "$OPTIONS"

while true; do
    case "$1" in
        -v|--verbose)
            VERBOSE=1
            shift
            ;;
        -o|--output)
            OUTPUT_FILE="$2"
            shift 2
            ;;
        -e|--environment)
            ENV="$2"
            shift 2
            ;;
        --)
            shift
            break
            ;;
        *)
            echo "Internal error!" >&2
            exit 1
            ;;
    esac
done

# Remaining arguments (if any)
# for arg in "$@"; do
#     echo "Remaining argument: $arg"
# done

echo "Script configuration:"
echo "Verbose mode: $VERBOSE"
echo "Output file: $OUTPUT_FILE"
echo "Environment: $ENV"

# Example usage of parsed arguments
if [ "$ENV" == "production" ]; then
    echo "Running in production environment."
else
    echo "Running in $ENV environment."
fi

if [ $VERBOSE -eq 1 ]; then
    echo "Verbose output enabled."
fi

echo "Writing logs to $OUTPUT_FILE"
How it works: This script demonstrates how to parse command-line arguments in bash using `getopt`. It supports both short (`-v`, `-o file`) and long (`--verbose`, `--output file`) options, allowing developers to create more flexible and configurable scripts. Default values are set, and arguments are processed in a `while` loop, updating variables like `VERBOSE`, `OUTPUT_FILE`, and `ENV` based on user input. This makes scripts reusable for different scenarios or environments without manual editing.

Need help integrating this into your project?

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

Hire DigitalCodeLabs