Skip to main content
InterviewHubPRO
Section Overview
Q13

Question 13 of 50

Part 2: Core Architecture & Implementation (Mid-Level)

26%
Bash & Shell Scripting (50 Qs)•Part 2: Core Architecture & Implementation (Mid-Level)

How do you parse command-line flags and options using `getopts`?

senior LevelCode ExampleSystem Design

In Simple Words: getopts is a built-in utility for parsing short CLI options (e.g. ./script.sh -f input.txt -v):

bash
#!/usr/bin/env bash
verbose=false
file=""

while getopts "f:v" opt; do
  case "$opt" in
    f) file="$OPTARG" ;;
    v) verbose=true ;;
    \?) echo "Invalid option -$OPTARG" >&2; exit 1 ;;
  esac
done
shift $((OPTIND - 1)) # Discard parsed options, leaving positional args
  • Colons after a letter (f:) indicate that the flag requires an argument value.