Problem Statement
What is getopts used for in bash scripts?
Explanation
Getopts parses command-line options (-a, -b, etc.) providing standard interface for script options. Syntax: while getopts "optstring" VAR; do ... done. Optstring defines valid options, colon after option indicates it requires argument. Example: "ab:c" accepts -a, -b with argument, -c. Current option in $VAR, argument in $OPTARG.
Example:
```bash
while getopts "f:o:v" opt; do
case $opt in
f) INPUT_FILE=$OPTARG;;
o) OUTPUT_FILE=$OPTARG;;
v) VERBOSE=1;;
\?) echo "Invalid option"; exit 1;;
esac
done
shift $((OPTIND-1)) # Remove processed options
# Remaining arguments in $@
```
Getopts handles: option bundling (-abc same as -a -b -c), option arguments (-f file or -ffile), invalid option errors (?), required argument errors (:). Leading colon in optstring enables silent error reporting: while getopts ":ab:" opt enables custom error handling.
Advantages over manual parsing: standard behavior, handles edge cases, cleaner code. Limitations: only single-character options (use getopt command for long options like --help). Understanding getopts enables professional command-line interfaces matching Unix conventions.
