Repository navigation
clean-up: move all shell script code to a function and use a "main" #740
Description
Activity
- addedP3Low-impact bugs or featuresLow-impact bugs or featuresgood first issueGood for newcomersGood for newcomerstype:discussionOpen ended discussion topicOpen ended discussion topictype:enhancementNew framework feature or requestNew framework feature or request
on Jul 14, 2021 - added a commit that references this issue
on Jul 26, 2021 - added 2 commits that reference this issue
on Oct 15, 2021 - changed the title
[-]clean-up: move all shell scripts code to a function[/-][+]clean-up: move all shell script code to a function[/+]on Jan 11, 2022 - changed the title
[-]clean-up: move all shell script code to a function[/-][+]clean-up: move all shell script code to a function and use a "main"[/+]on Apr 24, 2024 - added 2 commits that reference this issue
on Apr 9, 2025 Simon Tatham agrees with one more point
https://hachyderm.io/@simontatham/114511220670677410With a normal shell script, it's dangerous to edit the script file while an instance of the shell is still running it, because the shell will read from the modified version of the file starting at the file position it had got to in the old one, perhaps reading a partial command or the wrong command and doing something you didn't want.
But with a script in this style, the shell finishes reading the script before it does anything, so it's safe to edit.{ main "$@"; exit $? }The last, compound statement
{ }forces bash to read it entirely before running it.https://google.github.io/styleguide/shellguide.html#function-location
Don’t hide executable code between functions. Doing so makes the code difficult to follow and results in nasty surprises when debugging.
- added a commit that references this issue
on Apr 15, 2026
This a very generic, clean-up task. Its main purpose is to document this good practice: almost all the code in a shell script should be in a function. In other words, the smallest script should look like this:
Rationales:
local. This reduces the risk of accidentally overwriting some user environment variables (side effects)main "$@"line andsourcethe entire file without running it to test individual functions interactively (almost like the usual Python's__main__trick)if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then run_main; fiAnd last but not least, stating the obvious:
cc: