BASH
Parsing Script Arguments with Getopts
Learn how to parse command-line options and arguments in Bash scripts using `getopts`, enabling flexible and user-friendly script execution with various parameters.
#!/bin/bash
# Usage: script.sh [-v] [-f FILE] [-d DIRECTORY] ARG1 ARG2...
VERBOSE=0
FILE=""
DIRECTORY=""
while getopts "vf:d:" opt; do
case $opt in
v)
VERBOSE=1
echo "Verbose mode enabled."
;;
f)
FILE="$OPTARG"
echo "File specified: $FILE"
;;
d)
DIRECTORY="$OPTARG"
echo "Directory specified: $DIRECTORY"
;;
\?)
echo "Invalid option: -$OPTARG" >&2
exit 1
;;
esac
done
shift $((OPTIND-1)) # Shift positional parameters past the options
echo "Remaining arguments (non-options): $*"
if [ "$VERBOSE" -eq 1 ]; then
echo "Verbose output: Doing something with $FILE and $DIRECTORY"
fi
# Example usage: script.sh -v -f myfile.txt -d /tmp arg1 arg2
How it works: This script demonstrates how to parse command-line options and their arguments using `getopts`. It defines flags (`-v` for verbose, `-f` for file, `-d` for directory) and handles their values, then shifts the remaining positional arguments. This makes scripts more flexible and easier to use for varied tasks.