BASH
Parse Command Line Arguments with getopts for Script Customization
Learn to build robust bash scripts that accept and parse command-line arguments using `getopts`, enabling flexible execution with options and values.
#!/bin/bash
# Default values
VERBOSE=0
ACTION="default"
FILENAME="output.txt"
print_usage() {
echo "Usage: $0 [-v] [-a <action>] [-f <filename>]
"
echo " -v: Enable verbose mode."
echo " -a: Specify an action (e.g., 'deploy', 'build'). Default: '$ACTION'."
echo " -f: Specify output filename. Default: '$FILENAME'.
"
exit 1
}
# Parse options using getopts
while getopts "va:f:h" opt; do
case $opt in
v)
VERBOSE=1
;;
a)
ACTION="$OPTARG"
;;
f)
FILENAME="$OPTARG"
;;
h)
print_usage
;;
?)
print_usage
;;
esac
done
# Shift off the options and their arguments, so remaining arguments are accessible
shift "$(($OPTIND - 1))"
echo "Script configuration:"
echo "Verbose mode: $VERBOSE"
echo "Action: $ACTION"
echo "Output filename: $FILENAME
"
# Example usage of parsed variables
if [ "$ACTION" == "deploy" ]; then
if [ "$VERBOSE" -eq 1 ]; then
echo "Executing deployment in verbose mode..."
fi
echo "Deploying to production..."
# Add deployment logic here
elif [ "$ACTION" == "build" ]; then
echo "Building project..."
# Add build logic here
else
echo "Performing default action."
fi
echo "Script finished."
How it works: This script demonstrates how to parse command-line arguments using the `getopts` built-in command. It allows the script to accept short options like `-v` for verbose mode, `-a` for an action with a value, and `-f` for a filename with a value, each with default settings. A `print_usage` function provides help. This makes bash scripts much more flexible and user-friendly, allowing users to customize behavior without modifying the script's code.