Parse -n NAME and -v in a Bash script, declaring that -n requires an argument.
Which getopts invocation is appropriate?
In getopts optstring, a colon immediately after a letter means that option requires an argument; the value is placed in OPTARG.
Detailed explanation
getopts "n:v" optCorrect. n: requires an argument and v does not.
Correct. n: requires an argument and v does not.
getopts "nv:" optIncorrect. This makes v require an argument instead of n.
Incorrect. This makes v require an argument instead of n.
getopt "n:v"Incorrect. getopt is an external utility, not the Bash builtin form requested.
Incorrect. getopt is an external utility, not the Bash builtin form requested.
getopts "-n NAME -v" optIncorrect. optstring contains option letters and colons, not usage text with spaces.
Incorrect. optstring contains option letters and colons, not usage text with spaces.
Try it yourself
An example you can run in a temporary verification environment.
bash --noprofile --norc -c 'while getopts "n:v" opt; do printf "%s:%s\n" "$opt" "${OPTARG-}"; done' demo -n alice -vExpected result
n:aliceの後にv:Key points
- Short-option optstring
- : means required argument
- OPTARG holds the value
Notes
- Environment: GNU Bash 5.2 / Bash組込みgetopts
- Command output formatting can vary slightly by distribution or tool version.
- Run the example in a temporary directory or process when possible.
Foundation review
Read the scope first
Check whether the command acts on the current shell, a new process, an existing process, or a file.
Verify the observable result
Use the supplied command and compare the output with the expected result.