Interview Scripting (Bash, Groovy)

How do you parse command-line options with getopts? [Intermediate]

Answer

getopts is Bash's built-in way to parse short command-line options. It iterates through options, sets the option name in a variable, and uses OPTARG for option values when the option requires an argument.

Technical explanation

The option string controls which options are valid; a colon after an option means it requires a value.

After parsing, shift $((OPTIND - 1)) removes processed options so positional arguments remain.

getopts handles short options like -e prod -v. For long options like --environment, many teams use a manual case loop or external getopt carefully.

Hands-on example

env="dev"

verbose=false

while getopts ":e:v" opt; do

case "$opt" in

e) env="$OPTARG" ;;

v) verbose=true ;;

:) echo "option -$OPTARG requires a value" >&2; exit 2 ;;

\?) echo "unknown option -$OPTARG" >&2; exit 2 ;;

esac

done

shift $((OPTIND - 1))

echo "env=$env verbose=$verbose remaining=$*

Preparing for an interview?

Check how well your resume matches the role with our free resume checker— match score, ATS check, and the skills you're missing.

More Scripting (Bash, Groovy) interview questions

← All Scripting (Bash, Groovy) questions