Defining shell functions (define function)
Grammar:
[ function ] funname [()]{ action; [return int;]}说明:1. 可以带function fun() 定义,也可以直接fun() 定义,不带任何参数。2. 参数返回,可以显示加:return 返回,如果不加,将以最后一条命令运行结果,作为返回值。 return后跟数值n(0-255)。
Example (test_fun.sh):
#!/bin/shfSum 3 2;fSum(){ echo $1,$2; return $(($1+$2));}fSum 5 7;total=$(fSum 3 2);echo $total,$?;
From the above example we can get a few conclusions:
- The function must be declared before the function is called, and the shell script runs on a line-by-row basis. does not pre-compile like any other language. You must declare the function first before using the function.
- total=$ (fsum 3 2); With this method of invocation, it is clear that in the shell, inside the parentheses, it can be: a command statement. Therefore, we can consider a function in the shell as defining a new command, which is a command, so the individual input parameters are separated directly by a space. Once, the command inside the parameter method can be obtained by: $ ... $n. $ A represents the function itself.
- function return value, can only be obtained through the system variable, directly through =, get is a null value. In fact, we follow the above understanding that the function is a command, in the shell to obtain the command return value, all need to get through the $?
function scope, variable action range
Example (test_fun2.sh):
#!/bin/shecho $(uname);declare num=1000;uname(){ echo "test!"; ((num++)); return 100;}testvar(){ local num=10; ((num++)); echo $num;}uname;echo $?echo $num;testvar;echo $num;
Let's analyze the above example together to get the following conclusion:
- The definition function can be the same as the system command, when the shell Search command, the first will be found in the current shell file defined location, find the direct execution.
- Need to get function value: obtained by $?
- If you need to pass out other types of function values, you can define the variables (this is the global variable) before the function call. It can be modified directly inside the function, and then the modified value can be read out when the function is executed.
- If you need to define your own variable, you can define it in the function: local variable = value, when the variable is an internal variable, and its modification does not affect the value of the same variable outside the function.
Linux Shell Custom functions (definition, return value, variable scope) Introduction