Bird
Raised Fist0
Bash Scriptingscripting~10 mins

Option parsing with getopts in Bash Scripting - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Option parsing with getopts
Start script
↓
Initialize getopts
↓
Read next option
↓
Option found?
No→Exit loop
Yes↓
Match option with case
↓
Execute option action
↓
Loop back to read next option
The script starts and initializes getopts to read options one by one. For each option found, it matches and executes the related action, looping until no more options.
Execution Sample
Bash Scripting
while getopts ":ab:" opt; do
  case $opt in
    a) echo "Option a set" ;;
    b) echo "Option b set with value $OPTARG" ;;
    ?) echo "Invalid option: -$OPTARG" ;;
  esac
done
This script reads options -a and -b (which requires a value). It prints messages based on the options given.
Execution Table
StepOPTINDoptOPTARGActionOutput
11aMatch 'a' caseOption a set
22bvalueMatch 'b' caseOption b set with value value
34?xInvalid optionInvalid option: -x
45No more options
💡 No more options to process, getopts returns false and loop ends
Variable Tracker
VariableStartAfter 1After 2After 3Final
OPTIND12455
optab?
OPTARGvaluex
Key Moments - 3 Insights
Why does getopts use OPTIND and how does it change?
OPTIND is the index of the next argument to process. It starts at 1 and increments after each option is read, as shown in the execution_table under OPTIND.
What happens when getopts encounters an invalid option?
getopts sets opt to '?' and OPTARG to the invalid option character. The script can handle this case to show an error message, as in step 3 of the execution_table.
Why does option 'b' have a value and 'a' does not?
In the getopts string ':ab:', the colon after 'b' means it requires a value. So when 'b' is found, OPTARG holds its value, shown in step 2.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of OPTARG at step 2?
A"a"
B"value"
C"b"
D"x"
💡 Hint
Check the OPTARG column in row for step 2 in execution_table
At which step does getopts detect an invalid option?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look for the row where opt is '?' in execution_table
If option 'a' required a value, how would the execution_table change?
AOPTARG would hold a value for 'a'
BOPTARG would be empty for 'a'
Copt would be '?' for 'a'
DOPTIND would not increment
💡 Hint
Recall that options with ':' require a value, setting OPTARG accordingly
Concept Snapshot
Use getopts in a while loop to parse options.
Options with ':' require a value, stored in OPTARG.
OPTIND tracks the next argument index.
Use case to handle each option.
'?' handles invalid options.
Loop ends when no more options.
Full Transcript
This visual execution shows how bash's getopts parses command-line options. The script loops, reading one option at a time. OPTIND starts at 1 and moves forward after each option. For each option, the script matches it in a case statement and runs code. Options with a colon require a value, stored in OPTARG. If an invalid option is found, opt is set to '?'. The loop ends when getopts finds no more options. Variables OPTIND, opt, and OPTARG change step by step as shown. This helps beginners see exactly how option parsing works in bash scripts.

Practice

(1/5)
1. What is the main purpose of the getopts command in bash scripting?
easy
A. To read input from a file
B. To parse command-line options and their arguments easily
C. To execute commands in parallel
D. To create new files automatically

Solution

  1. Step 1: Understand the role of getopts

    getopts is a built-in bash command designed to handle command-line options and their arguments in scripts.
  2. Step 2: Compare with other options

    Other options like executing commands or reading files are not related to option parsing, which is the specific task of getopts.
  3. Final Answer:

    To parse command-line options and their arguments easily -> Option B
  4. Quick Check:

    getopts = option parsing [OK]
Hint: Remember: getopts reads options, not files or commands [OK]
Common Mistakes:
  • Confusing getopts with file reading commands
  • Thinking getopts runs commands in parallel
  • Assuming getopts creates files
2. Which of the following is the correct syntax to start parsing options with getopts in a bash script?
easy
A. while getopts "ab:" opt; do case $opt in a) echo "Option a" ;; b) echo "Option b with $OPTARG" ;; esac; done
B. for opt in getopts "ab:"; do echo $opt; done
C. if getopts "ab:" opt; then echo $opt; fi
D. getopts -a -b

Solution

  1. Step 1: Identify correct getopts usage

    The correct way to use getopts is inside a while loop with a case statement to handle each option.
  2. Step 2: Check each option

    The correct syntax uses while getopts "ab:" opt; do ... case $opt in a)... b)... esac; done. Other options use invalid control structures like for or if, or incorrect command syntax.
  3. Final Answer:

    while getopts "ab:" opt; do case $opt in a) echo "Option a" ;; b) echo "Option b with $OPTARG" ;; esac; done -> Option A
  4. Quick Check:

    while + getopts + case = correct syntax [OK]
Hint: Use while loop with getopts and case for options [OK]
Common Mistakes:
  • Using for loop instead of while
  • Missing case statement for options
  • Incorrect getopts command syntax
3. What will be the output of the following script if run as ./script.sh -a -b value?
while getopts "ab:" opt; do
  case $opt in
    a) echo "Option a set" ;;
    b) echo "Option b set with $OPTARG" ;;
  esac
done
medium
A. Option a set Option b set with value
B. Option a set Option b set with -b
C. Option b set with value
D. No output

Solution

  1. Step 1: Analyze the command line arguments

    The script is called with -a and -b value. Option a has no argument, b requires an argument.
  2. Step 2: Trace getopts parsing

    getopts processes the arguments sequentially. It first encounters -a, sets $opt to a, and echoes Option a set Option a set Option b set with -b set with value set. Next, -b value sets $opt to b and $OPTARG to value, echoing Option a set Option b set with -b set with value.
  3. Final Answer:

    Option a set Option b set with value -> Option A
  4. Quick Check:

    Options a and b with argument = output A [OK]
Hint: Remember colon means option needs argument [OK]
Common Mistakes:
  • Confusing option argument with option name
  • Ignoring option arguments
  • Assuming options print nothing
4. Given this snippet:
while getopts "ab:" opt; do
  case $opt in
    a) echo "Option a" ;;
    b) echo "Option b with $OPTARG" ;;
    ?) echo "Invalid option" ;;
  esac
done

What is the problem if the script is run with -b but no argument?
medium
A. getopts will crash with syntax error
B. getopts will ignore -b and continue silently
C. getopts will treat -b as option without argument and print "Option b with"
D. getopts will set opt to '?' and print "Invalid option"

Solution

  1. Step 1: Understand getopts behavior for missing argument

    If an option that requires an argument (like b:) is given without one, getopts sets opt to '?' to indicate an error.
  2. Step 2: Check case handling

    The case statement has a '?' option that echoes "Invalid option". So the script will print that message.
  3. Final Answer:

    getopts will set opt to '?' and print "Invalid option" -> Option D
  4. Quick Check:

    Missing argument triggers '?' and error message [OK]
Hint: Missing argument triggers '?' option in getopts [OK]
Common Mistakes:
  • Assuming getopts crashes on missing argument
  • Thinking option is accepted without argument
  • Ignoring '?' case in script
5. You want to write a script that accepts options -f (file name) and -v (verbose flag). Which getopts string and case structure correctly handle these options, where -f requires an argument and -v does not?
hard
A. getopts string: "fv"; case: v) verbose=1 ;; f) file=$OPTARG ;;
B. getopts string: "fv:"; case: f) file=$OPTARG ;; v) verbose=1 ;;
C. getopts string: "vf:"; case: v) verbose=1 ;; f) file=$OPTARG ;;
D. getopts string: "vf"; case: f) file=$OPTARG ;; v) verbose=1 ;;

Solution

  1. Step 1: Determine correct optstring

    Option -f requires an argument, so it must be followed by a colon: f:. Option -v is a flag, no colon needed. The correct string has ':' immediately after 'f', such as "vf:". Strings like "fv:" place ':' after 'v', making -v require an argument, which is wrong; missing ':' means no arguments expected.
  2. Step 2: Match case statement to options

    Case must handle v by setting verbose flag and f by assigning $OPTARG to file variable. getopts string: "vf:"; case: v) verbose=1 ;; f) file=$OPTARG ;; matches this correctly.
  3. Final Answer:

    getopts string: "vf:"; case: v) verbose=1 ;; f) file=$OPTARG ;; -> Option C
  4. Quick Check:

    Option with colon needs argument, flag no colon [OK]
Hint: Put colon after options needing arguments only [OK]
Common Mistakes:
  • Placing colon after flag option
  • Swapping option letters and arguments
  • Not assigning $OPTARG for options needing arguments
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard