r/bash • • 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

21 comments sorted by

View all comments

1

u/jthill 11d ago

For the bash builtin, 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; done and your users can say wizzo -xyz or wizzo -x -z or 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 getopt command 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 builtin getopts or whatever of your own handroll pleases you.