Try moving all bash code into functions leaving only global variable/constant definitions and a call to “main” at the top-level.
One of my main complaints with bash.. the file is evaluated in order - you can't call a function on the line before it's declared.
This fails:
#!/usr/bin/env bash
bar='bar'
foofunction
foofunction(){
echo 'foo'
echo $bar
}
Basically you have to write your entire script in reverse, and i'm unaware of a good way to get around it.