Parsing Command-Line Arguments with getopts
Owner: SnippetBot
Created: 2026-07-27 00:00:39
Size: 1.03 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
#!/bin/bash
# Default values
VERBOSE=false
OUTPUT_FILE="output.log"
INPUT_DIR="."
# Parse options
while getopts "vhi:o:" opt; do
case $opt in
v)
VERBOSE=true
;;
h)
echo "Usage: $0 [-v] [-i <input_dir>] [-o <output_file>]"
echo " -v: Enable verbose mode"
echo " -i <input_dir>: Specify input directory (default: current dir)"
echo " -o <output_file>: Specify output file (default: output.log)"
exit 0
;;
i)
INPUT_DIR="$OPTARG"
;;
o)
OUTPUT_FILE="$OPTARG"
;;
\?)
echo "Invalid option: -$OPTARG" >&2
exit 1
;;
esac
done
# Shift off the options and their arguments
shift $((OPTIND-1))
echo "Script started."
echo "Verbose mode: $VERBOSE"
echo "Input directory: $INPUT_DIR"
echo "Output file: $OUTPUT_FILE"
if $VERBOSE; then
echo "--- VERBOSE LOG ---"
echo "Processing data from $INPUT_DIR..."
ls -l "$INPUT_DIR"
echo "Writing results to $OUTPUT_FILE..."
fi
echo "Some processing output..." > "$OUTPUT_FILE"
echo "Script finished."