BASH
Parsing Command-Line Arguments with Getopts
Learn to parse command-line options and arguments efficiently in Bash scripts using 'getopts', enabling flexible configuration for your automated tasks.
#!/bin/bash\n\n# Default values for options\nVERBOSE=false\nOUTPUT_FILE="default_output.txt"\nCONFIG_PATH="/etc/app/config.ini"\n\n# Usage function\nusage() {\n echo "Usage: $0 [-v] [-o <file>] [-c <path>] [input_directory]" 1>&2\n echo " -v Enable verbose mode." 1>&2\n echo " -o <file> Specify output file (default: ${OUTPUT_FILE})." 1>&2\n echo " -c <path> Specify configuration file path (default: ${CONFIG_PATH})." 1>&2\n echo " input_directory Optional. Directory to process (default: current directory)." 1>&2\n exit 1\n}\n\n# Parse options using getopts\nwhile getopts ":vo:c:" opt; do\n case "${opt}" in\n v ) VERBOSE=true\n ;;\n o ) OUTPUT_FILE="$OPTARG"\n ;;\n c ) CONFIG_PATH="$OPTARG"\n ;;\n \? ) # Invalid option\n echo "Error: Invalid option -${OPTARG}" 1>&2\n usage\n ;;\n : ) # Missing argument for option\n echo "Error: Option -${OPTARG} requires an argument." 1>&2\n usage\n ;;\n esac\ndone\n\n# Shift positional parameters so that $1 refers to the first non-option argument\nshift "$(($OPTIND - 1))"\n\n# Get the first positional argument (if any), default to current directory\nINPUT_DIRECTORY="${1:-.}"\n\necho "Script Configuration:"\necho " Verbose Mode: ${VERBOSE}"\necho " Output File: ${OUTPUT_FILE}"\necho " Config Path: ${CONFIG_PATH}"\necho " Input Directory: ${INPUT_DIRECTORY}"\n\n# Example usage of variables based on parsed arguments\nif ${VERBOSE}; then\n echo "[DEBUG] Verbose mode is enabled."\nfi\n\necho "Processing data from ${INPUT_DIRECTORY} and writing to ${OUTPUT_FILE}..."\n# Add your main script logic here, using $VERBOSE, $OUTPUT_FILE, $CONFIG_PATH, $INPUT_DIRECTORY\n\n# Example: touch "$OUTPUT_FILE" # Create the output file
How it works: This Bash snippet demonstrates how to parse command-line arguments using `getopts`. It allows scripts to accept short options (e.g., `-v`, `-o <file>`) with or without arguments. The `while getopts` loop processes each option, and the `case` statement handles different flags. `OPTARG` holds the argument for options that require one, and `OPTIND` helps `shift` positional parameters to access non-option arguments. This is crucial for creating flexible and user-friendly automation scripts, allowing web developers to customize behavior for deployments, data processing, or build steps.