In Linux Shell, you can define functions and call them in shell scripts. The following describes the definition method and the precautions for calling it.
1. Define the shell function (define function)
Syntax:
[Function] funname [()]
{
Action;
[Return int;]
}
Note:
1. It can be defined with function fun () or fun () without any parameters.
2. If the parameter is returned, the value "+: Return" is displayed. If no value is added, the result of the last command is run as the return value. Return followed by value n (0-255
Instance (testfun1.sh ):
14 |
testfun1.sh: line 3: fSum:
command not found |
From the example above, we can draw several conclusions:
1. You must declare the function before calling the function. The shell script runs on a line-by-line basis. It does not pre-compile like other languages. You must declare the function before using the function.
2. Total = $ (fsum 3 2); through this call method, we know that in Shell single brackets, it can be a command statement.
Therefore, we can think of a function in shell as a new command, which is a command. Therefore, each input parameter is directly separated by a space.
Once, the command can get the parameter method through: $0... $ N. $0 indicates the function itself.
3. The function return value can only be passed through $? The system variable is obtained directly through =, and the result is a null value. In fact, according to the above understanding, we know that a function is a command. To obtain the return value of a command in shell, we need to use $? .
Ii. Function scope and scope of Variables
Let's first look at an instance (testfun2.sh ):
Let's analyze the above example and draw the following conclusions:
1. The definition function can be the same as the system command. It indicates that when a shell SEARCH Command is executed, it will first be searched in the defined location of the current shell file.
2. You need to obtain the function value through $? Obtain
3. If other types of function values need to be transferred, you can define the variable before calling the function (this is the global variable ). You can directly modify the value within the function, and then read the modified value after executing the function.
4. If you need to define your own variables, you can define the local variable = value in the function. In this case, the variable is an internal variable. Its modification will not affect the value of the same variable outside the function.
In my work, I have summarized some experiences in Linux and Shell functions. Do you have any suggestions!