Shell function, function parameter passing, function scope, recursion, library creation
One, Shell function
Format the command sequence together
Easy to reuse command sequence
1.1 Shell function definition
function 函数名 {
命令序列
}
函数名 () {
命令序列
}
function db1 {
read -p "请输入: " value
return $[$value*2] return表示退出函数并返回一个退出值
}
db1 调用这个函数(调用函数必写的)
echo $? 查看退出值,不写这步不会显示结果
db1 () {
read -p "请输入: " value
echo $[$value * 2]
}
result=`db1`
echo $result
Function return value: return means exiting the function and returning an exit value, which can be displayed by the $? variable in the script
1.2 Principles of use
1. Take the return value as soon as the function ends, because the $? variable only returns the exit status code of the last command executed
2. The exit status code must be 0-255, and the value will be divided by 256 if it exceeds
Two, function parameter transfer
sum1 () {
sum=$[$1 + $2]
echo $sum
}
read -p "输入第一个参数: " first
read -p "输入第二个参数: " second
sum1 $first $second
sum2 () {
sum=$[$1 + $2]
echo $sum
}
sum2 $1 $2
-----------------
abc.sh xxx xxx
Three, the scope of function variables
Functions in Shell scripts are only valid in the current Shell environment
Variables in Shell scripts are global by default
Use the local command to limit the variable to the function
myfun () {
local i 设置局部变量
i=8
echo $i
}
------------------------------
i=9 全局环境
myfun
echo $i
#!/bin/bash
abc () {
local i 设置局部变量
i=8
echo $i
}
-----------------------------
i=9 全局环境
abc
echo $i
Four, recursion
Function calls its own function
factorial
fact () {
if [$1-eq 1 ]
then
echo 1
else
local temp=$[$1-1]
local result=$ (fact $temp) 这里是一个新的函数,初始值是$temp,所以下面一步的$1变成了$temp
echo $[$1 * $result] 这里变化的一直是$1,$result始终为1
# 5 * $result (4*$result (3*$result (2*$result (1) )))
fi
}
read -p "请输入: " n
result=$ (fact $n)
echo $result
n=5
fact 5 fact 4 fact 3 fact 2 fact 1
$1=5 4 3 2 1
Five, recursive directory
function list_files () {
for f in 'ls $1'
do
if [-d "$1/$f" ] 判断$1下的$f是不是目录
then
echo "$2$f" 是目录就输出这个目录,空格是为了好区分父子目录
list_files "$1/$f" " s2" 然后在在$1/$f($1/$f在这里已经变成了$1)这一层目录下再判断$f($f是一个新的赋值)是不是目录
else
echo "$2$f" 不是目录就输出$f结果
fi
done
}
list_files "/var/log" ""
Six, create a library
vim myfuncs.sh
jiafa () {
echo $[$1 + $2]
}
chengfa () {
echo $[$1 * $2]
}
chufa () {
if [$2 -ne 0];then
echo $[$1 / $2]
else
echo "$2不能为0"
fi
}
vim test.sh
. myfuncs.sh
value1=10
value2=5
result1=`jiafa $value1 $value2`
result2=`chengfa $value1 $value2`
result3=`chufa $value1 $value2`
echo "加法结果为: $result1"
echo "乘法结果为: $result2"
echo "除法结果为: $result3"