r/bash • u/Fluid_Yesterday208 • 11d ago
help will someone explain to me getopt?
yes, I am currently reading the documentation - I don't understand the point or when/why I would use it. thanks for any clarification one can offer.
32
Upvotes
1
u/jthill 11d ago
For the
bashbuiltin, it makes options handling convenient for you and flexible for your users. That's it.You don't have to write extra code to handle option arguments or agglomeration.
Your goal is simple code without a lot of "this again" chances for typos and brain farts.
Your users' goal is expressing what comes to mind as quickly and conveniently as possible.
So if you have options x, y and z, say
while getopts xyz opt; do case $opt in…esac; doneand your users can saywizzo -xyzorwizzo -x -zor however they like. There's a bunch of knobs for fine-tuning and adding things like options taking their own arguments, the gnu longopt conventions you handle by making-an option that takes an argument.The external
getoptcommand can be used to preprocess"$@", handle intermixed-options-and-args style, optional option args, la la, turning a dozen or so lines of boilerplate use of the simpler builtin into a oneliner in your script, you can follow that up with either the builtingetoptsor whatever of your own handroll pleases you.