Parsing Command Line Arguments with Getopts in Bash
Owner: SnippetBot
Created: 2026-09-19 00:01:11
Size: 2.59 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#!/bin/bash
# Configuration / Default values
OUTPUT_FILE="output.txt"
VERBOSE=false
ACTION="default"
COUNT=1
# Function to display script usage
usage() {
echo "Usage: $0 [-f <file>] [-a <action>] [-c <count>] [-v] [-h]"
echo " -f <file> Specify an output file (default: $OUTPUT_FILE)"
echo " -a <action> Specify an action to perform (e.g., 'deploy', 'test', 'build')"
echo " -c <count> Specify a numerical count (default: $COUNT)"
echo " -v Enable verbose mode"
echo " -h Display this help message"
exit 0
}
# --- Main Script Logic ---
# Use getopts for parsing short options
# ':' after an option means it requires an argument
# 'h' for help, 'v' for verbose
# 'f:' for file, 'a:' for action, 'c:' for count
while getopts "hvf:a:c:" opt; do
case "${opt}" in
h)
usage
;;
v)
VERBOSE=true
echo "Verbose mode enabled."
;;
f)
OUTPUT_FILE="${OPTARG}"
;;
a)
ACTION="${OPTARG}"
;;
c)
# Basic validation for count to be a number
if [[ "$OPTARG" =~ ^[0-9]+$ ]]; then
COUNT="${OPTARG}"
else
echo "Error: Count must be a number." >&2
usage
fi
;;
:)
echo "Error: Option -${OPTARG} requires an argument." >&2
usage
;;
?)
echo "Error: Invalid option -${OPTARG}." >&2
usage
;;
esac
done
# Shift off the options and their arguments, so that "$@" refers to the remaining non-option arguments.
shift $((OPTIND -1))
echo "--- Script Configuration ---"
echo "Output File: $OUTPUT_FILE"
echo "Action: $ACTION"
echo "Count: $COUNT"
echo "Verbose: $VERBOSE"
if [ -n "$@" ]; then
echo "Remaining arguments (non-options): $@"
fi
echo "--------------------------"
# Example logic based on parsed arguments
case "$ACTION" in
deploy)
echo "Initiating deployment for $COUNT times to $OUTPUT_FILE..."
# Add deploy specific logic
;;
test)
echo "Running tests $COUNT times with output to $OUTPUT_FILE..."
# Add test specific logic
;;
build)
echo "Building project $COUNT times..."
# Add build specific logic
;;
*)
echo "Performing default action."
for i in $(seq 1 $COUNT); do
echo "Hello from default action ($i/$COUNT)!" >> "$OUTPUT_FILE"
done
echo "Default output written to $OUTPUT_FILE"
;;
esac
echo "Script finished."