BASH
Basic Command Line Argument Parsing in Bash
Implement simple command-line argument parsing in your Bash scripts to accept flags and values, making your scripts more flexible and user-friendly for various operations.
#!/bin/bash
# Script demonstrating basic command-line argument parsing
# Default values
NAME="World"
VERBOSE=false
INPUT_FILE=""
# Parse command-line options
# ':' after an option indicates it requires an argument.
# The leading ':' in the optstring makes getopts silent about errors,
# allowing custom error handling via '?' and ':' cases.
while getopts ":n:vf:" opt; do
case ${opt} in
n )
NAME="$OPTARG"
;;
v )
VERBOSE=true
;;
f )
INPUT_FILE="$OPTARG"
;;
\? )
echo "Invalid option: -$OPTARG" >&2
exit 1
;;
: )
echo "Option -$OPTARG requires an argument." >&2
exit 1
;;
esac
done
shift $((OPTIND -1)) # Shift positional parameters past the options
# Script logic based on parsed arguments
echo "Hello, $NAME!"
if [ "$VERBOSE" = true ]; then
echo "Verbose mode is enabled."
echo "Input file: ${INPUT_FILE:-'Not specified'}"
fi
if [ -n "$INPUT_FILE" ]; then
if [ -f "$INPUT_FILE" ]; then
echo "Processing file: $INPUT_FILE"
# Add file processing logic here
else
echo "Error: Input file '$INPUT_FILE' not found." >&2
exit 1
fi
fi
# Remaining arguments (if any)
if [ $# -gt 0 ]; then
echo "Remaining arguments: $*"
fi
# Example Usage:
# ./myscript.sh -n "Alice" -v
# ./myscript.sh -f data.txt
# ./myscript.sh -n "Developer" -v -f project.config arg1 arg2
How it works: This script demonstrates basic command-line argument parsing using `getopts`. It defines options like `-n` (for name), `-v` (verbose mode), and `-f` (for input file). The `while getopts` loop processes each option, setting variables based on flags and their arguments. `shift $((OPTIND -1))` removes the parsed options from the positional parameters, allowing access to any remaining non-option arguments. Includes basic error handling for invalid options or missing arguments.