BASH
Parse Command-Line Arguments with Getopts for Flexible Bash Scripts
Learn to parse short command-line options and their arguments in Bash using `getopts`, enabling more powerful and user-friendly script interactions for developers.
#!/bin/bash
# Default values
VERBOSE=false
ENVIRONMENT="development"
OUTPUT_FILE="output.txt"
# Usage function
usage() {
echo "Usage: $0 [-v] [-e <environment>] [-o <output_file>]"
echo " -v: Enable verbose output"
echo " -e <environment>: Set the environment (e.g., production, staging)"
echo " -o <output_file>: Specify an output file path"
exit 1
}
# Parse options using getopts
# v: no argument
# e: requires an argument
# o: requires an argument
while getopts "ve:o:" opt; do
case "$opt" in
v)
VERBOSE=true
;;
e)
ENVIRONMENT="$OPTARG"
;;
o)
OUTPUT_FILE="$OPTARG"
;;
\?) # Invalid option
usage
;;
esac
done
# Shift positional parameters so that $1 refers to the first non-option argument
shift $((OPTIND-1))
echo "Script execution with parameters:"
echo "Verbose mode: $VERBOSE"
echo "Environment: $ENVIRONMENT"
echo "Output File: $OUTPUT_FILE"
# Example of using a positional argument (if any)
if [ -n "$1" ]; then
echo "First positional argument: $1"
fi
# Example logic based on parsed arguments
if $VERBOSE; then
echo "Verbose output enabled: Performing detailed operations..."
fi
if [ "$ENVIRONMENT" == "production" ]; then
echo "Running in PRODUCTION environment."
else
echo "Running in $ENVIRONMENT environment."
fi
echo "Results will be written to $OUTPUT_FILE"
# echo "Some actual script logic writing to $OUTPUT_FILE..." > "$OUTPUT_FILE"
How it works: This script demonstrates how to parse command-line options and arguments using `getopts`. It defines a `usage` function for help, then processes flags like `-v` (verbose) and options with arguments like `-e` (environment) and `-o` (output file). `getopts` automatically handles argument extraction (`$OPTARG`) and invalid options, making scripts more user-friendly and configurable.