Passing arguments to a function
We started demonstrating what a function looks like by showing you a simple script, the simplest we could create. We still haven't defined how to talk to your function, and we still don't know how to give a function some parameters or arguments and get something in return. In this recipe, we are going to fix that.
Getting ready
Since we mentioned arguments, we need to talk a little about them. bash
treats arguments in functions the same as it does in the script itself—arguments become local variables inside the function block. To return a value, we also do almost exactly the same as when we need to deal with the whole script—we simply return a value from our function block and then read it inside the main script body.
Remember when we said you can reference arguments that were given to your script when it was initially called, and that we used variables called $1
, $2
, $3
, and so on to get the first, second, third,...