Why do we wrap script logic in a `main` function and call `main "$@"` at the end?
AdvancedConceptShells, scripts and execution
Answer
Three reasons:
- Bash reads and executes a script incrementally. If someone edits or replaces the file while it runs, the running shell can read garbage from the new offset. With everything in functions, the whole file is parsed before
mainexecutes. - Functions can be defined in any order and
localvariables keep state contained. - The file can be sourced by tests without running:
[[ "${BASH_SOURCE[0]}" == "$0" ]] && main "$@".
More on Shells, scripts and execution
What is a shell, and how is Bash different from sh, dash and zsh?BeginnerWhat does the shebang line do, and why prefer `#!/usr/bin/env bash` over `#!/bin/bash`?BeginnerWhat is the difference between `./script.sh`, `bash script.sh` and `source script.sh`?BeginnerWhat happens when you type a command name? How does Bash decide what to run?AdvancedWhy must `cd`, `export` and `read` be builtins rather than external programs?IntermediateWhat is the difference between a login, interactive and non-interactive shell, and which startup files run?Intermediate