Shell programming function (detailed introduction)
table of Contents
One, the role of shell functions
Write the command sequence together in a format to facilitate repeated use of the command sequence
Second, the format of the shell function
1. Shell function definition
Format 1:
unction 函数名 {
命令序列
}
Format 2:
函数名 (){
命令序列
}
2. Function return value
return means to exit the function and return an exit value, which can be displayed by the $? variable in the script
Principle of Use
- The return value is taken as soon as the function ends, because the $? variable only returns the exit status code of the last command executed
- The exit status code must be 0~255, and the value will be divided by 256 if it exceeds
Example:
Three, function parameter transfer
Example 1:
Example 2:
Fourth, 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
Example 1:
#!/bin/bash
abc () {
a=5
b=6
echo "c等于$c"
}
a=8
c=9
abc
echo "a等于$a"
echo "b等于$b"
Example 2:
#!/bin/bash
abc () {
local i
i=8
echo "inside $i"
}
i=9
abc
echo "outside $i"
Example 3:
#!/bin/bash
abc () {
echo "inside1 $i"
let i++
local i
i=8
echo "inside2: $i"
}
i=9
abc
echo "outside $i"
~
Five, recursion
Function calls its own function
1. Factorial
1、[root@localhost ~]#vim 7.sh
#!/bin/bash
fact () {
if [ $1 -eq 1 ]
then
echo 1
else
local temp=$[$1 - 1]
local result=$(fact $temp)
echo "$[$1*$result]"
fi
}
read -p "请输入阶乘数:" n
result=`fact $n`
echo "$result"
2、[root@localhost ~]#. 7.sh
请输入阶乘数:5
120
[root@localhost ~]#
2. Recursive directory
#!/bin/bash
function list_files {
for f in `ls $1`
do
if [ -d "$1/$f" ]
then
echo "$2$f"
list_files "$1/$f" "$2"
else
echo "$2$f"
fi
done
}
list_files "/var/log" ""
Six, function library
1、[root@localhost ~]#vim 9.sh
#!/bin/bash
jiafa () {
result=$[$1 + $2]
echo $result
}
jianfa () {
result=$[$1 - $2]
echo $result
}
chengfa () {
result=$[$1 * $2]
echo $result
}
chufa () {
if [ $2 -ne 0 ]
then
result=$[$1 / $2]
echo $result
else
echo "$2不能等于0!"
fi
2、[root@localhost ~]#vim 10.sh
#!/bin/bash
. ~/9.sh
read -p "输入第一个参数值:" first
read -p "输入第二个参数值:" second
result1=`jiafa $first $second`
result2=`jianfa $first $second`
result3=$(chengfa $first $second)
result4=$(chufa $first $second)
echo $result1
echo $result2
echo $result3
echo $result4
3、[root@localhost ~]#vim 10.sh
[root@localhost ~]#. 10.sh
输入第一个参数值:10
输入第二个参数值:30
40
-20
300
0