8

I am using the FUNCNAME array variable that gives us various executing functions' name. While using it, I came across main function inside ${FUNCNAME[max_ind]}.

Where is this main function defined in our shell script? What code is written inside main and how can I use it? Basically all the information of this main function.

1 Answers1

14

It's the main level of the shell script.

FUNCNAME itself seems specific to Bash, and its man page says this:

An array variable containing the names of all shell functions currently in the execution call stack. The element with index 0 is the name of any currently-executing shell function. The bottom-most element (the one with the highest index) is "main". This variable exists only when a shell function is executing.

Which means it could get confusing too, since e.g. this script:

#!/bin/bash
main() {
        foo
}
foo() {
        declare -p FUNCNAME;
}
main

would print

declare -a FUNCNAME=([0]="foo" [1]="main" [2]="main")

even though the two mains are not the same function.

Note that it's not that far-fetched to explicitly create a function called main. Having a dedicated main function might help with structuring the code, since it's probably easier to read a script where the main program is in one place and not perhaps scattered here and there on the top level between other function definitions.

There's also the idiom of putting everything in functions and calling main "$@"; exit on the main level to make sure that if the script file is modified during execution, it won't affect the running script. See: How to read the whole shell script before executing it?

I don't know why Bash has chosen to use main there, instead of something that would stand out more, like the __main__ that Python uses for a similar use.

ilkkachu
  • 138,973
  • ‘I don't know why Bash has chosen to use main there’: TBH, this is yet another thing on a long list of things bash does that make me immediately think ‘Why would you do that?’. Top of the list is invocation as /bin/sh not actually being strictly compatible with POSIX (you still get a bunch of extensions). – Austin Hemmelgarn Sep 18 '21 at 01:37
  • 2
    @AustinHemmelgarn, having the compatibility mode still support extensions that don't clash with any standard behaviour (but would e.g. just be syntax errors in a standard shell) more like makes me think "why would one not do that". But that's a discussion that seems a bit off-topic here. – ilkkachu Sep 18 '21 at 08:42