News for hackers. Stuff that matters.
Re:Better bash in 15 minutes by Karunamon on Wednesday April 16, 2014 @01:21PM (#7599101)
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.
Re:Better bash in 15 minutes by nfoz on Wednesday April 16, 2014 @05:18PM (#7600589)
Well, what would you do instead? It's an interpreted language. When you type "foofunction" at a prompt, you don't want it to wait around in case you define that to have meaning later.

You probably want the interpreter to be smart: "Am I loading a script from a file, or am I receiving instructions interactively on the command-line?" But now there's two modes of execution, and code in a bash script won't work if you type it into the prompt yourself. That's a bit uncomfortable.

Re:Better bash in 15 minutes by xrt on Wednesday April 16, 2014 @02:48PM (#7599700)
I really hate writing things in reverse, but a decent style in Bash is to put everything in functions, w/ a main() at the top:

    #! /usr/bin/env bash
    set -e -u
    bar='bar'
    
    main() {
      foofunction
    }
    
    foofunction() {
      echo 'foo'
      echo $bar
    }

    main "$@"
Re:Better bash in 15 minutes by 14113 on Wednesday April 16, 2014 @01:41PM (#7599232)
C is the same, but at least with C it's possible to declare functions before providing definitions. Is it possible that it's the same in bash?