BASH
Advanced CLI Argument Parsing with getopts
Build powerful, configurable bash scripts with `getopts`. This snippet demonstrates parsing short and long options, handling arguments for robust script execution.
#!/bin/bash
# Default values
VERBOSE=false
ENVIRONMENT="development"
CONFIG_FILE="default.conf"
# Function to display help message
display_help() {
echo "Usage: $0 [OPTIONS]"
echo " -v Enable verbose output."
echo " -e <env> Specify environment (e.g., 'production', 'staging'). Default: development"
echo " -c <file> Specify configuration file path. Default: default.conf"
echo " -h Display this help message."
echo
echo "Example: $0 -v -e production -c /etc/app/prod.conf"
exit 0
}
# Parse short options using getopts
while getopts ":ve:c:h" opt; do
case $opt in
v) VERBOSE=true ;;
e) ENVIRONMENT="$OPTARG" ;;
c) CONFIG_FILE="$OPTARG" ;;
h) display_help ;;
\?)
echo "Invalid option: -$OPTARG" >&2
display_help
;;
:)
echo "Option -$OPTARG requires an argument." >&2
display_help
;;
esac
done
shift $((OPTIND-1)) # Shift positional parameters to exclude options
# Handle remaining arguments (if any)
if [ "$#" -gt 0 ]; then
echo "Unexpected arguments: $@" >&2
display_help
fi
# Script logic using parsed options
echo "--- Script Configuration ---"
echo "Verbose: $VERBOSE"
echo "Environment: $ENVIRONMENT"
echo "Config File: $CONFIG_FILE"
echo "----------------------------"
if $VERBOSE; then
echo "Running in verbose mode..."
fi
echo "Executing main logic for '$ENVIRONMENT' using '$CONFIG_FILE'..."
# Add your main script logic here
# e.g., deploy to a specific environment, run tests with a config
How it works: This bash snippet demonstrates how to parse command-line arguments using `getopts`, a powerful built-in utility for handling short options (e.g., `-v`, `-e <value>`). It includes handling for arguments that require values, provides a help message, and gracefully manages invalid options or missing arguments. This makes scripts highly configurable and user-friendly, essential for automating web development tasks like deployments, builds, or environment-specific operations.