Passing parameters to a Bash function

前端 未结 7 1246
北荒
北荒 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:52

    I hope this example can help you. It takes two numbers from the user, feeds them to the function called add (in the very last line of the code), and add will sum them up and print them.

    #!/bin/bash
    
    read -p "Enter the first  value: " x
    read -p "Enter the second value: " y
    
    add(){
        arg1=$1 #arg1 gets to be the first  assigned argument (note there are no spaces)
        arg2=$2 #arg2 gets to be the second assigned argument (note there are no spaces)
    
        echo $(($arg1 + $arg2))
    }
    
    add x y #feeding the arguments
    

提交回复
热议问题