-
Notifications
You must be signed in to change notification settings - Fork 59
Open
Labels
P3Low-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
Description
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:
main()
{
do stuff
}
# The braces and bottom position let you safely edit the script while it's running
# https://hachyderm.io/@simontatham/114511220670677410
# (XKCD 303)
{
main "$@"; exit "$?"
}Rationales:
- More variables can be
local. This reduces the risk of accidentally overwriting some user environment variables (side effects) - Functions can be defined in any order, they don't need to be defined before being used
- It provides more line numbers in the FUNCNAME stack on failure
- moving code around functions does not change the indentation level which helps with git diff, rebase, cherry-pick, merge...
- it's very easy to comment out the last,
main "$@"line andsourcethe entire file without running it to test individual functions interactively (almost like the usual Python's__main__trick) - Similarly, it's very easy to copy/paste functions into an interactive shell and test them.
- It's easy to temporarily turn off an entire function call for local testing purposes by commenting out a single line.
- For the same reason, better testability, example: https://opensource.com/article/19/2/testing-bash-bats
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then run_main; fi - https://en.wikipedia.org/wiki/Margin_(typography)#The_Digital_Page "Although margin-less web pages do still exist, today it is generally understood that having wide enough margins to provide adequate white space around text is important to the usability and readability of digital text" (unverified)
And last but not least, stating the obvious:
- A sequence of calls to well named functions is much more readable than a giant and anonymous concatenation of all these functions.
cc:
- https://hachyderm.io/@simontatham/114511220670677410
- https://google.github.io/styleguide/shellguide.html#main
- https://google.github.io/styleguide/shellguide.html#function-location
- https://steve-yegge.blogspot.com/2006/03/execution-in-kingdom-of-nouns.html
- [sof-test] add set -e to all test cases (Unless You Love Debugging) #312
Metadata
Metadata
Assignees
Labels
P3Low-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