main function
By convention, a function called main that holds a program's top-level steps and is called once at the end of the file.
In more detail
Putting the steps in main keeps the order of the program readable and avoids stray global variables. In Python and Bash it is only a convention, whereas languages such as C, Go and Java require a main function as the program's starting point. A Bash script calls it on the last line with main "$@", so nothing runs until the whole file has been read. Python programs usually call it from a main guard so that importing the file does not run it.
Example
def main():
...
main()Related terms
- shell function — A named group of commands, defined as name() { ...; }, that you then run like any other command.
- local variable — A variable that exists only inside one function call and cannot be seen or changed from outside it.
- dollar at — The special parameter $@, which in double quotes expands to every argument, or array element with ${arr[@]}, as a separate word.
- main guard — The line if __name__ == "__main__": which runs the block beneath it only when the file is run as a program, not when it is imported.
- function — A named, reusable block of code that takes inputs, called arguments, and can return a result.
- flow of control — The order in which a program's statements actually run, which jumps into functions, round loops and past if branches rather than going straight down the page.
Taught in
- Style That Prevents Bugs — Bash Scripting & Command Line Automation
- Several Functions, And Flow Of Control — Hands-on Python: Complete Video Course & Book
- Function Parameters — Hands-on Python: Complete Video Course & Book
- Multiple Parameters — Hands-on Python: Complete Video Course & Book
- Sample Graphics Programs — Hands-on Python: Complete Video Course & Book
- Composing Web Pages In Python — Hands-on Python: Complete Video Course & Book