No, the functions have to exist in the shells environment at the time of calling them.
Google's "Shell Style Guide" has a fix for this:
A function called main
is required for scripts long enough to contain at least one other function.
At the very end of the script, after all functions, as the only statement not in a function, you would have
main "$@"
This would call the main
function with whatever parameters the script was given. The main
function could be located at the top of the script (the style guide says to put it at the bottom, but then again, it says many things).
When the shell gets to the main
call, all functions in the script have been parsed and can therefore be called from within the main
function.
[[ ${BASH_SOURCE[0]} = "$0" ]] && Main "$@"
to call the main function so I can source it in another script withoutMain
being executed. Then I can either reuse the functions or write tests to check them. – BlackJack Jun 13 '18 at 14:10main "$@"; exit
(withexit
on the same line asmain
) is also useful as a safeguard against the file being modified while it is interpreted. – Stéphane Chazelas Jun 13 '18 at 15:03exit
on the same line asmain
we make sure the shell won't read anything again from the file aftermain
returns. – Stéphane Chazelas Jun 13 '18 at 15:45main "$@"; exit
as the last line in the file do thatmain "$@"
wouldn't do? OTOH,main "$@"; exit $?
would allowmain()
toreturn
a value that would be passed as the exit status of the script, so that actually adds some value. – Monty Harder Jun 13 '18 at 16:32main; exit
,main; exit $?
ormain <EOF>
, in all cases the exit code ofmain
is used as the exit code of the script. Theexit
would be just to prevent things getting messed up if someone edits the script while it's running. – ilkkachu Jun 13 '18 at 16:36