1

Google Shell Style Guide says "don't hide executable code between functions" and "put the main program in a function called main as the bottom most function".

Where should we place the getopts commands for parsing command line arguments to a script? Should they be wrapped in a function dedicated to parsing the arguments to the script (parsing arguments to a script by parsing arguments to a function defined in the script, sounds a little complicated to understand), wrapped in the main function, or directly placed somewhere in the script (in this case, how can we avoid placing them between function definitions)?

If you've got functions, put them all together near the top of the file. Only includes, set statements and setting constants may be done before declaring functions.

Don't hide executable code between functions. Doing so makes the code difficult to follow and results in nasty surprises when debugging.

A function called main is required for scripts long enough to contain at least one other function. In order to easily find the start of the program, put the main program in a function called main as the bottom most function. This provides consistency with the rest of the code base as well as allowing you to define more variables as local (which can't be done if the main code is not a function). The last non-comment line in the file should be a call to main:

main "$@"

Obviously, for short scripts where it's just a linear flow, main is overkill and so is not required.

closed as primarily opinion-based by Kusalananda, muru, Stephen Harris, Thomas Dickey, Fabby Nov 22 '18 at 12:52

Many good questions generate some degree of opinion based on expert experience, but answers to this question will tend to be almost entirely based on opinions, rather than facts, references, or specific expertise. If this question can be reworded to fit the rules in the help center, please edit the question.

  • I would put it in main. Or, you could put it after the functions, before calling main. – ctrl-alt-delor Nov 22 '18 at 12:32

Browse other questions tagged or ask your own question.