Shell custom function
The syntax format of the Shell function definition is as follows:
Function name () {
Statements
[return value]
}
Description of each part:
Function is a keyword in Shell that is used specifically to define functions.
Name is the name of the function
Statements is the code that the function executes, that is, a set of statements
Return value represents the return value of the function, where return is the Shell keyword and is specifically used in the function to return a value; this part can be written or unwritten.
The part surrounded by {} is called the function body, and calling a function actually executes the code in the function body.
A simplified method of function definition
If you find it troublesome, you can define the function without the function keyword:
Name () {
Statements
[return value]
}
If you write the function keyword, you can also omit the parentheses after the function name:
Function name {
Statements
[return value]
}
I suggest using the standard writing method, so that you can "see the name and know the meaning" and understand it at a glance.
Function call
You can pass parameters to the Shell function or not when you call it. If you do not pass parameters, just give the name of the function:
Name
If you pass parameters, multiple parameters are separated by spaces:
Name param1 param2 param3
No matter which form it is, the function name does not need to be followed by parentheses.
Unlike other programming languages, the Shell function cannot specify parameters when defined, but it can pass parameters when it is called, and it receives whatever parameters are passed to it.
Shell also does not limit the order of definitions and calls, you can put the definition before the call, or vice versa, the definition after the call.
Example demonstration
1) define a function that outputs the address of the Shell tutorial:
#! / bin/bash
# function definition
Function url () {
Echo "http://c.biancheng.net/shell/"
}
# function call
Url
Running result:
Http://c.biancheng.net/shell/
You can put the call in front of the definition, that is, in the following form:
#! / bin/bash
# function call
Url
# function definition
Function url () {
Echo "http://c.biancheng.net/shell/"
}
2) define a function that calculates the sum of all parameters:
#! / bin/bash
Function getsum () {
Local sum=0
For n in $@
Do
((sum+=n))
Done
Return $sum
}
Getsum 10 20 55 15 # calls the function and passes parameters
Echo $?
Running result:
one hundred