In Shell scripts, functions can be used to encapsulate a piece of reusable code that can be called multiple times, thereby improving the maintainability and reusability of the script.
Functions can divide large projects into small pieces for execution, improving the readability of the code.
The definition of a function usually has the following format:
function_name() {
# 函数体
...
}
Among them, function_name
is the function name, the parentheses can contain the parameter list, and the function body contains the implementation code.
zzr () {
a=1
b=2
c=$(($a+$b))
echo $c
}
zzr
The result is obviously 3
return value
Return value: return
The return range in the shell is 0-255. If it exceeds 255, it will be modulated by 256.
When a function has return, the return value is the internal execution result of the function, so the value of echo $? is also 3, which has nothing to do with right or wrong.
The function of the return value: used to determine whether subsequent code is executed normally
Function parameter passing
Internal parameter transfer
First assign the value (read -p), then call the method (ky32), and the function passes the value to the command sequence (sum calculation)
External parameters
Need to enter variables externally
scope of function variables
sh f.sh
9 9 of global variables
8 Internal variables do not change
10 let i++
Listen to internal commands without local 9 8 8
There are local variables that need to be listened to globally.
(b is a global change and will not be affected)
function recursion
The essence is to use yourself
pow () {
if [ $a -ne 0 ]
then
let sum=sum*b
a=$(($a-1))
pow $a $b
fi
}
sum=1
read -p "输入指数:" a
read -p "输入底数:" b
pow $a $b
echo "$sum"
Calculate factorial
zzr () {
if [ $1 -eq 1 ]
then
echo 1
else
local temp=$(($1-1))
local result=$(zzr $temp)
echo "$(($1*$result))"
fi
}
read -p "输入一个数" a
result=`zzr $a`
echo $result