Is it possible to call a function which is declared below in bash?
Example
if [ "$input" = "yes" ]; then
YES_FUNCTION
elif [ "$input" = "no" ]; then
NO_FUNCTION
else
exit 0;
fi
YES_FUNCTION()
{
.....
.....
}
NO_FUNCTION()
{
.....
.....
}
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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 "<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1b3f5b">[email protected]</a>"; exit
When we call main at the end of file, all functions are already defined. Explicitly passing "[email protected]" 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?)
Method 2
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
mainis 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 "<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="87a3c7">[email protected]</a>"
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.
Method 3
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.
Method 4
The shell has no concept of declaring a function. So you cannot have a forward declaration.
As a consequence, you need to have the function implementation read by the shell before it can be called.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0