Interview Prep/Shell Scripting/Shells, scripts and execution

Why do we wrap script logic in a `main` function and call `main "$@"` at the end?

AdvancedConceptShells, scripts and execution
Answer

Three reasons:

  1. 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 main executes.
  2. Functions can be defined in any order and local variables keep state contained.
  3. The file can be sourced by tests without running: [[ "${BASH_SOURCE[0]}" == "$0" ]] && main "$@".
All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Shells, scripts and execution