0
0
Bash Scriptingscripting~5 mins

Option parsing with getopts in Bash Scripting - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the purpose of getopts in bash scripting?

getopts helps scripts read and handle command-line options (flags) easily and consistently.

It parses options like -a or -b value so your script can respond accordingly.

Click to reveal answer
beginner
How do you specify that an option requires an argument in getopts?

In the options string passed to getopts, add a colon : right after the option letter.

For example, getopts "a:b" means -a needs an argument, -b does not.

Click to reveal answer
intermediate
What variable does getopts use to store the current option letter?

getopts stores the current option letter in the shell variable given as its second argument (typically named opt).

OPTARG holds the argument value for options that require one, while OPTIND tracks the next index to process.

Click to reveal answer
intermediate
What does the variable OPTIND represent in getopts usage?

OPTIND is the index of the next argument to be processed by getopts.

It starts at 1 and increments as options are parsed, helping your script know where options end and positional arguments begin.

Click to reveal answer
beginner
Write a simple getopts loop to handle options -a (no argument) and -b (requires argument).
while getopts "ab:" opt; do
  case $opt in
    a) echo "Option a triggered" ;;
    b) echo "Option b with value: $OPTARG" ;;
    *) echo "Invalid option" ;;
  esac
done
Click to reveal answer
In getopts, how do you indicate that an option requires an argument?
AAdd a colon ':' after the option letter in the options string
BAdd a semicolon ';' after the option letter
CUse uppercase letters for options with arguments
DPut the option letter inside square brackets
Which variable holds the argument value for an option in getopts?
AOPTARG
BOPTIND
COPTVAL
DOPTOPT
What does OPTIND represent in getopts?
AThe total number of options parsed
BThe current option letter
CThe index of the next argument to process
DThe exit status of the last command
What happens if getopts encounters an unknown option?
AIt throws a syntax error
BIt stops the script immediately
CIt ignores the option silently
DIt sets the option variable to '?'
Which command correctly starts a getopts loop for options -x and -y with -y requiring an argument?
Awhile getopts "xy" opt; do ... done
Bwhile getopts "xy:" opt; do ... done
Cwhile getopts "x:y:" opt; do ... done
Dwhile getopts "x:y" opt; do ... done
Explain how to use getopts to parse command-line options in a bash script.
Think about how you tell the script which options need arguments and how you handle each option inside the loop.
You got /4 concepts.
    Describe the roles of OPTARG and OPTIND when using getopts.
    One stores values, the other tracks position.
    You got /3 concepts.