Forward function declarations in a Bash or a Shell script?

BashFunctionShForward Declaration

Bash Problem Overview


Is there such a thing in bash or at least something similar (work-around) like forward declarations, well known in C / C++, for instance?

Or there is so such thing because for example it is always executed in one pass (line after line)?

If there are no forward declarations, what should I do to make my script easier to read. It is rather long and these function definitions at the beginning, mixed with global variables, make my script look ugly and hard to read / understand)? I am asking to learn some well-known / best practices for such cases.


For example:

# something like forward declaration
function func

# execution of the function
func

# definition of func
function func
{
    echo 123
}

Bash Solutions


Solution 1 - Bash

Great question. I use a pattern like this for most of my scripts:

#!/bin/bash

main() {
    foo
    bar
    baz
}

foo() {
}

bar() {
}

baz() {
}

main "$@"

You can read the code from top to bottom, but it doesn't actually start executing until the last line. By passing "$@" to main() you can access the command-line arguments $1, $2, et al just as you normally would.

Solution 2 - Bash

When my bash scripts grow too much, I use an include mechanism:

File allMyFunctions:

foo() {
}

bar() {
}

baz() {
}

File main:

#!/bin/bash

. allMyfunctions

foo
bar
baz

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKiril KirovView Question on Stackoverflow
Solution 1 - BashJohn KugelmanView Answer on Stackoverflow
Solution 2 - BashmouvicielView Answer on Stackoverflow