Passing parameters to a Bash function

前端 未结 7 1281
北荒
北荒 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:58

    A simple example that will clear both during executing script or inside script while calling a function.

    #!/bin/bash
    echo "parameterized function example"
    function print_param_value(){
        value1="${1}" # $1 represent first argument
        value2="${2}" # $2 represent second argument
        echo "param 1 is  ${value1}" #as string
        echo "param 2 is ${value2}"
        sum=$(($value1+$value2)) #process them as number
        echo "The sum of two value is ${sum}"
    }
    print_param_value "6" "4" #space sparted value
    #you can also pass paramter durign executing script
    print_param_value "$1" "$2" #parameter $1 and $2 during executing
    
    #suppose our script name is param_example
    # call like this 
    # ./param_example 5 5
    # now the param will be $1=5 and $2=5
    

提交回复
热议问题