Forward function declarations in a Bash or a Shell script? Forward function declarations in a Bash or a Shell script? bash bash

Forward function declarations in a Bash or a Shell script?


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

#!/bin/bashmain() {    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.


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

File allMyFunctions:

foo() {}bar() {}baz() {}

File main:

#!/bin/bash. allMyfunctionsfoobarbaz