Having problems calling function within bash script

后端 未结 1 634
灰色年华
灰色年华 2020-12-20 07:52

I\'ve been working on our intro scripting assignment, and am having issues calling functions within the script. I am in the second portion of the assignment, and I am just t

相关标签:
1条回答
  • 2020-12-20 08:43

    Much like in C a function must be defined before it's used. In your code snippet you are calling part_two (which is calling part_five and part_six) before declaring the two functions.

    Have you tried moving their definitions to the start of the script?

    EDIT:

    In most cases, the best way to deal with this in Bash is to simply define all functions at the start of the script before executing any actual commands. The order of the definitions does not really matter - the shell only looks up a function when it's about to use it - so generally there are no dependency issues etc. that you may have to think about.

    EDIT 2:

    There are cases where you may not be able to just define a function at the start of the script. A common case is when you use conditional constructs to dynamically select or modify the declaration of a function e..g.:

    if [[ "$1" = 0 ]]; then
        function show() {
            echo Zero
        }
    else
        function show() {
            echo Not-zero
        }
    fi
    

    In these cases you have to make sure that each function call happens after that function (and any others that it calls) is declared.

    EDIT 3:

    In bash a function declaration is actually the function foo() { ... } block where you define its implementation - and yes, the function keyword is not strictly necessary. There are no function prototypes as in C - they would not make sense anyway because shell scripts are generally parsed as they are executed. Newer Bash version do read a script at once, but they mostly check for syntax errors and not for logical errors such as this one.

    BTW the official term is "function declaration", but even the Bash info page uses "declaration" and "definition" interchangeably.

    0 讨论(0)
提交回复
热议问题