The Linux shell can be user-defined, and can be invoked randomly in a shell script. Here's how it's defined, and what the call needs to pay attention to.
First, define the shell function (define functions)
Grammar:
[Function] funname [()]
{
Action
[Return int;]
}
Description
- 1, can be defined with function fun () or directly fun (), without any parameters.
- 2, the parameter returns, may display adds: Return returns, if does not add, will run the result with the last command, as the return value. return followed by value N (0-255
Instance (testfun1.sh):
#!/bin/sh
fsum 3 2;
function Fsum ()
{
echo $1,$2;
Return $ (($1+$2));
}
Fsum 5 7;
total=$ (fsum 3 2);
Echo $total, $?;
SH testfun1.sh
testfun1.sh:line 3:fsum:command not found
5,7
3,2
1
5
From the above example we can get a few conclusions:
- 1, must declare the function before calling the function place, the shell script is run row by line. Does not precompile like any other language. You must declare the function first before using the function.
- 2, total=$ (fsum 3 2); With this call method, we know clearly that inside the single bracket in the shell, it can be: a command statement. Therefore, we can consider the function in the shell as defining a new command, which is a command, so that each input parameter is separated directly by a space. Once, the command to get the parameters of the method can be passed: $ ... $n get. The $ $ represents the function itself.
- 3, function return value, only through $? The system variable is obtained, the direct pass =, the obtained is the null value. In fact, we follow the above understanding, know that the function is a command, in the shell to obtain the command return value, all need to pass the $?
Second, function scope, variable range of action
Let's look at an example (testfun2.sh):
#!/bin/sh
echo $ (uname);
declare num=1000;
Uname ()
{
echo "test!";
((num++));
return;
}
TestVar ()
{local
num=10;
((num++));
echo $num;
}
uname;
echo $?
echo $num;
TestVar;
echo $num;
SH testfun2.sh
Linux
test!
1001
1001
Let's analyze the example above, and we can get the following conclusion:
- 1, the definition function can be the same as the system command, the Shell Search command, first of all in the current shell file defined in place to find, find direct execution.
- 2, need to obtain function value: through $?
- 3. If you need to spread other types of function values, you can define the variable (this is the global variable) before the function call. You can modify it directly inside the function, and then you can read the modified value in the execution function.
- 4, if you need to define their own variables, you can define in the function: local variable = value, when the variable is an internal variable, its modification does not affect the value of the same variable outside the function.
These are my work on Linux, Shell functions using some experience summary, there is no mention of places, welcome to communicate!