In the shell, arguments can be passed to a function when it is called. Inside the function body, the value of the parameter is obtained in the form of a $n, for example, $ $ for the first argument, and $ = for the second argument ...
Examples of functions with parameters:
- #!/bin/bash
- Funwithparam () {
- Echo "The value of the first parameter is $!"
- Echo "The value of the second parameter is $!"
- Echo "The value of the tenth parameter is $!"
- Echo "The value of the tenth parameter is ${10}!"
- Echo "The value of the eleventh parameter is ${11}!"
- echo "The amount of the parameters is $#!" # Number of parameters
- Echo "The string of the parameters is $*!" # All arguments passed to the function
- }
- Funwithparam 1 2 3 4 5 6 7 8 9
To run the script:
The value of the first parameter is 1! The value of the second parameter is 2! The value of the tenth parameter is 10! The value of the tenth parameter is 34! The value of the eleventh parameter is 73! The amount of the parameters is 12! The string of the parameters is 1 2 3 4 5 6 7 8 9 34 73! "
Note that the $ $ cannot get the tenth parameter, and the tenth parameter requires ${10}. When n>=10, you need to use ${n} to get the parameters.
In addition, there are several special variables to handle the parameters, as mentioned earlier:
Special Variables |
Description |
$# |
The number of arguments passed to the function. |
$* |
Displays all arguments passed to the function. |
[Email protected] |
Same as $*, but slightly different, see Shell special variables. |
$? |
The return value of the function. |
Shell function parameters