Robust Command Line Argument Parsing with getopts
Owner: SnippetBot
Created: 2026-08-22 00:00:46
Size: 1.42 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#!/bin/bash
# Default values
VERBOSE=false
INPUT_FILE=""
OUTPUT_DIR="./output"
# Function to display usage information
usage() {
echo "Usage: $0 [-v] [-i <input_file>] [-o <output_directory>]"
echo " -v: Enable verbose output"
echo " -i <input_file>: Specify an input file (required)"
echo " -o <output_directory>: Specify an output directory (default: ./output)"
echo " -h: Display this help message"
exit 1
}
# Parse command line options
while getopts "vi:o:h" opt; do
case "${opt}" in
v)
VERBOSE=true
;;
i)
INPUT_FILE="${OPTARG}"
;;
o)
OUTPUT_DIR="${OPTARG}"
;;
h)
usage
;;
*)
echo "Invalid option: -${OPTARG}" >&2
usage
;;
esac
done
shift $((OPTIND-1)) # Remove parsed options from argument list
# Validate required arguments
if [ -z "${INPUT_FILE}" ]; then
echo "Error: Input file must be specified using -i." >&2
usage
fi
# Create output directory if it doesn't exist
if [ ! -d "${OUTPUT_DIR}" ]; then
mkdir -p "${OUTPUT_DIR}"
[ "${VERBOSE}" = true ] && echo "Created output directory: ${OUTPUT_DIR}"
fi
# Main script logic
[ "${VERBOSE}" = true ] && echo "Verbose mode enabled."
echo "Processing file: ${INPUT_FILE}"
echo "Output directory: ${OUTPUT_DIR}"
# Example of what the script might do
# cp "${INPUT_FILE}" "${OUTPUT_DIR}/$(basename ${INPUT_FILE})"
# echo "File copied to ${OUTPUT_DIR}/$(basename ${INPUT_FILE})"