7

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.

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.

3
  • 1
    I've learned something new today +1
    – roaima
    Sep 17 at 15:09
  • ‘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). Sep 18 at 1:37
  • 1
    @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 at 8:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.