0
0
Bash Scriptingscripting~10 mins

Option parsing with getopts in Bash Scripting - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to correctly initialize the option parsing loop using getopts.

Bash Scripting
while getopts [1] opt; do
  case $opt in
    h) echo "Help message"; exit 0;;
    *) echo "Invalid option"; exit 1;;
  esac
done
Drag options to blanks, or click blank then click option'
A"-h"
B"h"
C"a:b"
D"ab"
Attempts:
3 left
💡 Hint
Common Mistakes
Including a dash '-' in the option string.
Using multiple letters when only one is needed.
Adding a colon when the option does not take an argument.
2fill in blank
medium

Complete the code to correctly check if the option requires an argument.

Bash Scripting
while getopts "f[1]" opt; do
  case $opt in
    f) filename=$OPTARG;;
    *) echo "Unknown option"; exit 1;;
  esac
done
Drag options to blanks, or click blank then click option'
A:
Bf
Cg
Dh
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting the colon after the option letter that requires an argument.
Adding letters without colons for options that need arguments.
3fill in blank
hard

Fix the error in the option parsing loop to correctly handle unknown options.

Bash Scripting
while getopts "ab" [1]; do
  case $opt in
    a) echo "Option a";;
    b) echo "Option b";;
    *) echo "Unknown option: $opt"; exit 1;;
  esac
done
Drag options to blanks, or click blank then click option'
Aarg
Boptarg
Coption
Dopt
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different variable name after getopts than in the case statement.
Using $OPTARG instead of the option variable for case matching.
4fill in blank
hard

Fill both blanks to correctly parse options 'u' with argument and 'v' without argument.

Bash Scripting
while getopts [1] [2]; do
  case $opt in
    u) user=$OPTARG;;
    v) verbose=1;;
    *) echo "Invalid option"; exit 1;;
  esac
done
Drag options to blanks, or click blank then click option'
A"u:v"
B"uv"
Copt
Doptarg
Attempts:
3 left
💡 Hint
Common Mistakes
Not adding a colon after 'u' if it requires an argument.
Using a variable name different from 'opt' in the loop.
5fill in blank
hard

Fill all three blanks to create a dictionary of options and their arguments, skipping options without arguments.

Bash Scripting
declare -A opts
while getopts [1] [2]; do
  case $opt in
    u) opts[[3]]=$OPTARG;;
    v) opts[verbose]=1;;
    *) echo "Unknown option"; exit 1;;
  esac
done
Drag options to blanks, or click blank then click option'
A"u:v"
Bopt
C"user"
D"opt"
Attempts:
3 left
💡 Hint
Common Mistakes
Not using quotes around the dictionary key.
Using the wrong variable name after getopts.
Missing colon after option letter that requires argument.