function allows us to divide a complex function into several modules, which makes the program structure clearer and the code reuse more efficient. Like other programming languages, the Shell supports functions as well. The Shell function must be defined before use.
The Shell functions are defined in the following format:
Function_name () { List of commands [return value]}
If you prefer, you can also add keyword functions to the function name:
function function_name () { List of commands [return value]}
function return value, you can explicitly increment the return statement, if not added, the last command will run the result as the return value.
The Shell function return value can only be an integer, which is generally used to indicate success or failure of the function, 0 for success, and other values to fail. If you return other data, such as a string, you will often get an error message: "Numeric argument required".
If you have to make the function return a string, you can first define a variable to receive the result of the function, and the script accesses the variable when needed to get the function return value.
Let's look at an example:
- #!/bin/bash
- # Define your function here
- Hello () {
- Echo "Url is http://see.xidian.edu.cn/cpp/shell/"
- }
- # Invoke your function
- Hello
Operation Result:
$./test.shhello world$
The calling function only needs to give the function name, and no parentheses are required.
Then look at a function with a return statement:
- #!/bin/bash
- Funwithreturn () {
- echo "The function is to get the sum of the numbers ..."
- echo- n "Input first number:"
- Read Anum
- echo- n "Input Another number:"
- Read Anothernum
- echo "The numbers is $aNum and $anotherNum!"
- return $ (($aNum + $anotherNum))
- }
- Funwithreturn
- # Capture Value Returnd by the last command
- RET=$?
- echo "The sum of numbers is $ret!"
Operation Result:
The function is to get the sum of the numbers ... Input first Number:25input Another number:50the, numbers are and 50! The sum of numbers is 75!
function return value after calling this function through $? To obtain.
Let's look at an example of a function nesting:
- #!/bin/bash
- # Calling one function from another
- Number_one () {
- Echo "Url_1 is http://see.xidian.edu.cn/cpp/shell/"
- Number_two
- }
- Number_two () {
- Echo "url_2 is http://see.xidian.edu.cn/cpp/u/xitong/"
- }
- Number_one
Operation Result:
Url_1 is http://see.xidian.edu.cn/cpp/shell/Url_2 is http://see.xidian.edu.cn/cpp/u/xitong/
As with the delete variable, the delete function can also use the unset command, but add the. f option as follows:
- $unset . f function_name
If you want to invoke the function directly from the terminal, you can define the function in the. profile file in the home directory so that you can call it immediately after each login by entering the function name at the command prompt.
Shell Script Learning 22 Shell function: Shell function return value, delete function, call function at terminal