Challenge - 5 Problems
Getopts Guru
Get all challenges correct to earn this badge!
Test your skills under time pressure!
💻 Command Output
intermediate2:00remaining
What is the output of this getopts script?
Consider this bash script snippet using getopts to parse options. What will it print when run with arguments
-a -b value -c?Bash Scripting
#!/bin/bash while getopts "ab:c" opt; do case $opt in a) echo "Option a set";; b) echo "Option b set with value $OPTARG";; c) echo "Option c set";; *) echo "Invalid option";; esac done
Attempts:
2 left
💡 Hint
Remember that getopts processes options one by one and that options with a colon expect an argument.
✗ Incorrect
The script defines options 'a', 'b:' (which requires an argument), and 'c'. Running with '-a -b value -c' triggers all three options. The 'b' option prints its argument stored in $OPTARG.
💻 Command Output
intermediate2:00remaining
What error does this getopts usage produce?
What error or output results from running this script with arguments
-x?Bash Scripting
#!/bin/bash while getopts "ab:" opt; do case $opt in a) echo "Option a";; b) echo "Option b with $OPTARG";; *) echo "Unknown option: $opt";; esac done
Attempts:
2 left
💡 Hint
Check how getopts handles options not defined in the option string.
✗ Incorrect
When getopts encounters an unknown option, it sets the option variable to '?' and triggers the default case. The script prints 'Unknown option: x'.
📝 Syntax
advanced2:00remaining
Which option string correctly requires an argument for option 'f'?
You want to parse options where option 'f' requires an argument. Which option string is correct for getopts?
Attempts:
2 left
💡 Hint
In getopts, a colon after an option letter means it requires an argument.
✗ Incorrect
The colon after 'f' in "f:" tells getopts that 'f' requires an argument. Without the colon, 'f' is treated as a flag without argument.
🚀 Application
advanced2:00remaining
How to correctly shift positional parameters after getopts?
After parsing options with getopts, you want to remove the processed options from the positional parameters. Which command correctly shifts the parameters?
Attempts:
2 left
💡 Hint
OPTIND points to the next argument to be processed, so subtract 1 to shift processed options.
✗ Incorrect
OPTIND is the index of the next argument to be processed. To remove all processed options, shift by OPTIND minus 1.
🔧 Debug
expert3:00remaining
Why does this getopts script fail to parse option arguments correctly?
Given this script snippet, why does it fail to print the argument for option 'd' when run with
-d value?
#!/bin/bash
while getopts "d" opt; do
case $opt in
d) echo "Option d with argument $OPTARG";;
*) echo "Invalid option";;
esac
doneAttempts:
2 left
💡 Hint
Check the option string passed to getopts and how it indicates required arguments.
✗ Incorrect
The option string "d" means option 'd' does not expect an argument. To accept an argument, it should be "d:". Without the colon, OPTARG is never set.