Shell function-parameter passing, return value, recursion, function library (detailed explanations and illustrations that can be understood by the cobbler)
Recursion is the operation of a function calling its own function
Recursive factorial
The factorial of a positive integer is the product of all positive integers less than or equal to the number, and the factorial of 0 is 1. The factorial of the natural number n is written as n!
That is, n!=1×2×3×...×(n-1)×n. Factorial can also be defined recursively: 0!=1, n!=(n-1)!×n
[root@localhost~]# ./23.sh
输入你想要阶乘的数值:103628800[root@localhost~]# ./23.sh
输入你想要阶乘的数值:202432902008176640000[root@localhost~]# vim 23.sh
#!/bin/bash
qz(){
【函数名为qz】
if[ $1-ne 1];then 【进行位置参数1(输入的想要阶乘数值num)不等于1的判断】
local qz1=$[$1-1] 【定义变量qz1=位置参数1的值-1,并用local进行限定,使其只在函数内部可使用】
local qz2=`qz $qz1` 【定义变量qz2=函数qz里的变量qz1命令运行后的结果,并用反撇号进行提取,用local进行限定。
因为每次都需要获得位置参数1减1的值,所以不能直接qz2=qz1,需要定义为qz函数内的qz1值】
echo $[$1*$qz2] 【输出值为位置参数1*变量qz2的值】
else
echo 1
fi
}
read -p "输入你想要阶乘的数值:" num
qz $num 【将变量num传参到函数qz内】
Recursive directory
method one
When using wildcard *, when there is no file or directory, use * to indicate
[root@localhost~]# ./24.sh
输入你想要查询的目录名:/var/log
/var/log/anaconda:...略......略.../var/log/secure-20210309/var/log/speech-dispatcher:/var/log/speech-dispatcher/* 【前面2个空格以突显层级关系,通配符*代表该目录中无文件】
/var/log/tallylog
...略.../var/log/yum.log
[root@localhost~]# vim 24.sh
#!/bin/bash
qz(){
for w in $1/* 【用for循环输出参数1,通配符*代表输入的参数下所有的文件和子目录,并赋值给变量w】
doif[-d $w ];then 【用-d判断变量w是否为目录,因为变量w是输入的绝对路径】
echo "$2$w: " 【如果条件成立则输出变量w的值,这里的$2在第一次循环时是无值,则没有空格】
qz $w " $2" 【调用qz函数本身,当第二次递归操作时则有1个空格,第三次递归操作则有2个空格,以表示层级关系】
else
echo "$2$w" 【如果条件不成立,则输出第N此递归得到的空格及w的值】
fi
done
}
read -p "输入你想要查询的目录名:" dir
qz $dir "" 【将输入的值进行传参到qz函数内,第二个位置参数""用来缩进以区分子目录】
Way two
With ls, there is no display when there is no file or directory
[root@localhost~]# vim 24.sh
[root@localhost~]# ./24.sh
输入你想要查询的目录名:/var/log
...略......略...
tuned:
tuned.log
vmware-vgauthsvc.log.0[root@localhost~]# vim 24.sh
#!/bin/bash
qz(){
for w in $(ls $1)doif[-d $1/$w ];then
echo "$2$w: "
qz $1/$w " $2"else
echo "$2$w"
fi
done
}
read -p "输入你想要查询的目录名:" dir
qz $dir ""
Function library
Encapsulate frequently used repetitive codes into function library files
The function library is generally not executed directly, but called by other scripts