Forward function declarations in a Bash or a Shell script?

后端 未结 2 1674
野趣味
野趣味 2020-12-04 09:32

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

相关标签:
2条回答
  • 2020-12-04 10:00

    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.

    0 讨论(0)
  • 2020-12-04 10:14

    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
    
    0 讨论(0)
提交回复
热议问题