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 first be defined and then used
1. The Shell functions are defined in the following format:
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".
The calling function only needs to give the function name, and no parentheses are required.
The test examples are as follows:
#!/bin/sh#author:lottu#copyright (c) li0924.comfunction Lottu () {echo "HI Lottu" read-p "Please input your name:" Name echo "HI ${name}"}lottu #调用函数echo $? #打印函数执行结果执行结果如下:./fun01.shhi lottuplease Input your Name:li0924hi li09240
2. Delete a function
As with variables, the delete function can also use the unset command, but add the. f option as follows:
unset. F function_name
If you want to call a function directly from the terminal, you can define the function in the. profile file in the home directory so that you can immediately invoke the function name at the command prompt after each login.
3. Function parameters
In the shell, arguments can be passed to a function when it is called. Inside the function body, the value of the parameter is obtained in the form of a $n, for example, $ $ for the first argument, and $ for the second argument.
Note that the $ $ cannot get the tenth parameter, and the tenth parameter requires ${10}. When n>=10, you need to use ${n} to get the parameters. Dressing theory.
Shell Basics (ix) function