1)
Create
Function
Name {
...
}
Or:
Name (){
...
}
2)
Call
Use the function name directly. The function can be called only after it is defined;
When a function has the same name, the new definition will overwrite the old definition and no alarm is triggered;
3)
Exit
Use
Return
4)
Return Value
Function exit status, variable available
$?
Get --
$?
It is always the result of the last command. Therefore, the return value must be obtained as soon as possible after the function returns, otherwise it will be overwritten by the return of the new command;
L
The default return value is the return value of the last command;
L
Use"
Return n
"Return,
N
Is an integer in the range
0
~
255
;
TBD
, Can only be used
$?
Get results?
L
Use
Shell
Variable storage return value, which can be used for any type of Return Value -- Use
Echo
Output
Eg:
Function
A {
Echo "XXXX"
Read-T 3-P "input ......"
#
Output
Stdout
Of
Input something
Not part of the returned result
Echo 1000
Echo $…
}
Rlt = 'A'
#
The returned values are stored in
Rlt
Echo
$ Rlt
# Rlt
Is all
Echo
Output Combination
If the method in the example is used, the function is used as a sub-process.
Exit
It cannot be used to exit the script; in addition, it can still be used
$?
Obtain Functions
Return
(Or
Exit
;
TBD
: How to make some of them
Echo
Not as function output?
Method:
Echo
Redirect
Stderr
;
5)
Passing Parameters
Bash
Process a function as a small script. You can also pass the parameter named
$0
, The parameter is
$1
,
$2
And so on
Call Method for passing Parameters
Result = 'a 1 abc'
6)
Global Variables
By default, all variables defined in the script are global variables, and functions can access their externally defined variables-bad style
Eg:
Function
A {
C = dddd
#
Variables defined in the function
Echo $ C
}
C = 1111.
Echo
$ C
A
# C
Value changed
Echo
$ C
7)
Local variable, use
Local
Eg:
Function
A {
Local C = dddd
#
Define local variables
Echo $ C
}
C = 1111.
Echo
$ C
A
Echo
$ C
# C
Value is not function
A
Change
8)
Recursion
Eg
, Implement factorial
X! = X * (x-1 )!
Function
X {
If [$1-EQ 1]; then
Echo $1
Else
Local TMP = $ [$1-1]
Echo $[$1 * 'x $ TMP ']
Fi
}
Ret = 'x
5'
Echo $ RET
9)
Function library
Create: Write the function to an independent file, as shown in figure
AAA. t
Library problem: the function is the same as the environment variable, only when it is created
Shell
Valid;
Usage:
Source
Command in the current
Shell
To execute commands;
Source
Alias:
Dot operator
Not used
Source
Command to create a new
Shell
Execute commands to face the above problems;
Eg
, Reference
Aaa
Library:
.
./AAA. t
Source
The command is equivalent
# Include
Used to import files. Then, the functions in the file can be called directly.