Skip to main content
InterviewHubPRO
Section Overview
Q44

Question 44 of 50

Part 3: Advanced Text Processing & Production Internals (Senior / Lead)

88%
Bash & Shell Scripting (50 Qs)•Part 3: Advanced Text Processing & Production Internals (Senior / Lead)

Parsing Command-Line Options with `getopts`: Handling flags (`-f`), arguments (`-o value`), and help output.

senior LevelCode Examplebash-shellAdvanced Text Processing

In Simple Words: getopts is Bash's built-in POSIX option parser for handling short flags:

bash
#!/usr/bin/env bash

usage() { echo "Usage: $0 [-e <env>] [-v] [-h]"; exit 1; }

VERBOSE=0
ENV="development"

while getopts "e:vh" opt; do
  case "$opt" in
    e) ENV="$OPTARG" ;;
    v) VERBOSE=1 ;;
    h) usage ;;
    *) usage ;;
  esac
done
shift $((OPTIND - 1)) # Shift away parsed flags

echo "Environment: $ENV, Verbose: $VERBOSE"