Words do not say much, directly on the format:
function formats in the Linux shell:
function Myfunc () {
Action
[Return int;]
}
Among them, the individual thinks function and () are all functions of the flag, if you do not need to pass parameters , choose one can make myfunc represented as a function;
Procedural programming involves an important topic, code reuse, and the reusability of a piece of code is one of the most important metrics for measuring the level of program scripting.
Functions in the shell are also life-cycle:
Created when called and terminates upon return. Return is the flag that terminates the function execution. Once a return is present, the remaining content in the function is not executed.
If there is no return statement in the function, by default, the result of the execution of the last command in the function is returned.
Why does the function need to return a value?
The return value of the function differs from the execution result of the function;
Function execution result is optional, through the use of ECHO, print and other commands to output information;
The return value of the function, also the exit status code of the function, must exist, the default is the last command in the function exit status code, otherwise it will be implemented with return N (Note that n must be an integer)
Personally, the return value of the function allows us to make logical judgments in the script, by setting different return values in the function to achieve different logical decisions,
In order to achieve different functions, on the other hand, it is to implement the logic judgment inside the function, thus terminating the function execution.
Similar to most programming languages, functions in shell scripts can also pass parameters:
① How do I pass parameters?
When calling a function, the argument list is separated by a blank space after the function name;
Such as:
#!/bin/bash
Myfunc () {
echo "The first argument is $"
echo "The number of arguments is $#"
Return 4
}
Myfunc "Hello" "World"
Execution Result:
[Email protected]:/home/marvin/shell#./function.sh
The first argument is Hello
The number of arguments is 2
[Email protected]:/home/marvin/shell# echo $?]
4
② in the function body, what special variables can be referenced?
As in the preceding code, $ and $ #的使用:
We can use $ ... To refer to passing parameters,
Use $ A to refer to the relative path of the script;
Use $ #来引用传递参数的数目;
Use $* and [email protected] to refer to the overall parameters passed (the two are slightly different);
Everything is similar to the special variables that were born in the shell script.
Recursive implementation of the ③ function:
Shell script Function Chapter