BASH

Parse Command Line Arguments in Bash Scripts

Learn to create flexible and user-friendly bash scripts by implementing robust command-line argument parsing for flags and options with values.

#!/bin/bash
# Script to demonstrate parsing command line arguments using getopts

# Default values for options
VERBOSE=0
INPUT_FILE=""
OUTPUT_DIR="/tmp"
CONFIG_MODE="default"

# Function to display usage information
usage() {
  echo "Usage: $0 [-v] [-f <input_file>] [-o <output_dir>] [-m <mode>]"
  echo "  -v: Enable verbose output"
  echo "  -f <file>: Specify an input file (required)"
  echo "  -o <dir>: Specify an output directory (default: /tmp)"
  echo "  -m <mode>: Set configuration mode (e.g., dev, prod, test)"
  echo "Example: $0 -v -f data.txt -o /var/log -m prod"
  exit 1
}

# Parse command line options using getopts
# 'v' expects no argument
# 'f:' expects an argument (input file)
# 'o:' expects an argument (output directory)
# 'm:' expects an argument (mode)
while getopts "vf:o:m:" opt; do
    case $opt in
        v)
            VERBOSE=1
            echo "Verbose mode enabled."
            ;;
        f)
            INPUT_FILE="$OPTARG"
            ;;
        o)
            OUTPUT_DIR="$OPTARG"
            ;;
        m)
            CONFIG_MODE="$OPTARG"
            ;;
        \?)
            # If an unknown option is encountered or missing argument
            echo "Error: Invalid option or missing argument for -$OPTARG." >&2
            usage
            ;;
        :)
            # Missing argument for an option that requires one
            echo "Error: Option -$OPTARG requires an argument." >&2
            usage
            ;;
    esac
done

# Shift off the options and their arguments from the positional parameters
shift "$((OPTIND-1))"

# Check if input file is provided (it's a required argument in this example)
if [ -z "$INPUT_FILE" ]; then
    echo "Error: Input file must be specified using -f option." >&2
    usage
fi

# Display parsed values
echo "------------------------------------"
echo "Script execution parameters:"
echo "Verbose: $VERBOSE"
echo "Input File: $INPUT_FILE"
echo "Output Directory: $OUTPUT_DIR"
echo "Configuration Mode: $CONFIG_MODE"
echo "Remaining arguments (if any): $@"
echo "------------------------------------"

# Example of how you might use these variables later
if [ "$VERBOSE" -eq 1 ]; then
    echo "Processing '$INPUT_FILE' in '$CONFIG_MODE' mode..."
fi
mkdir -p "$OUTPUT_DIR" || echo "Warning: Could not create output directory $OUTPUT_DIR"

# ... rest of your script logic using $INPUT_FILE, $OUTPUT_DIR, $VERBOSE, etc.
How it works: This script demonstrates how to parse command-line arguments using the `getopts` built-in command in Bash. It allows defining short options (e.g., `-v`, `-f file.txt`) and handling arguments for those options. The `while getopts` loop processes each option, and a `case` statement assigns values to script variables. It also includes `usage` instructions and error handling for invalid options or missing arguments, making your scripts more user-friendly and robust.

Need help integrating this into your project?

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

Hire DigitalCodeLabs