Passing parameters to a Bash function

前端 未结 7 1250
北荒
北荒 2020-11-22 10:15

I am trying to search how to pass parameters in a Bash function, but what comes up is always how to pass parameter from the command line.

I would like to pass param

7条回答
  •  孤独总比滥情好
    2020-11-22 10:55

    There are two typical ways of declaring a function. I prefer the second approach.

    function function_name {
       command...
    } 
    

    or

    function_name () {
       command...
    } 
    

    To call a function with arguments:

    function_name "$arg1" "$arg2"
    

    The function refers to passed arguments by their position (not by name), that is $1, $2, and so forth. $0 is the name of the script itself.

    Example:

    function_name () {
       echo "Parameter #1 is $1"
    }
    

    Also, you need to call your function after it is declared.

    #!/usr/bin/env sh
    
    foo 1  # this will fail because foo has not been declared yet.
    
    foo() {
        echo "Parameter #1 is $1"
    }
    
    foo 2 # this will work.
    

    Output:

    ./myScript.sh: line 2: foo: command not found
    Parameter #1 is 2
    

    Reference: Advanced Bash-Scripting Guide.

提交回复
热议问题