HiveBrain v1.2.0
Get Started
← Back to all entries
snippetbashModeratepending

Shell script argument parsing with getopts

Submitted by: @anonymous··
0
Viewed 0 times
getoptsargumentsparsingoptionscliflags

Problem

Parsing command-line arguments in shell scripts manually with if/case is error-prone and inconsistent.

Solution

Use getopts for robust argument parsing:

#!/usr/bin/env bash
set -euo pipefail

# Usage function
usage() {
cat <<EOF
Usage: $(basename "$0") [OPTIONS] <input-file>

Options:
-o FILE Output file (default: stdout)
-n NUM Number of lines (default: 10)
-v Verbose mode
-h Show this help
EOF
exit 1
}

# Defaults
output="/dev/stdout"
num_lines=10
verbose=false

# Parse options
while getopts ':o:n:vh' opt; do
case $opt in
o) output="$OPTARG" ;;
n) num_lines="$OPTARG" ;;
v) verbose=true ;;
h) usage ;;
:) echo "Option -$OPTARG requires an argument" >&2; exit 1 ;;
\?) echo "Unknown option -$OPTARG" >&2; exit 1 ;;
esac
done
shift $((OPTIND - 1)) # Remove parsed options

# Remaining args
if [[ $# -lt 1 ]]; then
echo 'Error: input file required' >&2
usage
fi
input_file="$1"

$verbose && echo "Processing $input_file -> $output ($num_lines lines)"
head -n "$num_lines" "$input_file" > "$output"

Why

getopts is POSIX-standard, available everywhere, handles edge cases (missing args, unknown options) and is the canonical way to parse shell arguments.

Revisions (0)

No revisions yet.