call function declared below
Like others have said, you can't do that.
But if you want to arrange the code into one file so that the main program is at the top of the file, and other functions are defined below, you can do it by having a separate main
function.
E.g.
#!/bin/sh
main() {
if [ "$1" = yes ]; then
do_task_this
else
do_task_that
fi
}
do_task_this() {
...
}
do_task_that() {
...
}
main "$@"; exit
When we call main
at the end of file, all functions are already defined. Explicitly passing "$@"
to main
is required to make the command line arguments of the script visible in the function.
The explicit exit
on the same line as the call to main is not mandatory, but can be used to prevent a running script from getting messed up if the script file is modified. Without it, the shell would try to continue reading commands from the script file after main
returns. (see How to read the whole shell script before executing it?)
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.
No, functions have to be declared before they’re used. Shell scripts are read line by line and acted upon line by line; so a function doesn’t exist until its declaration has been executed.