Shell函数
Shell函数
-
将命令序列按格式写在一起
-
可方便重复使用命令序列
-
Shell函数定义
-
function 函数名 { 命令序列 } 或 函数名() { 命令序列 }
-
-
调用函数的方法
-
函数名 [参数1] [参数2]
-
函数返回值
return表示退出函数并返回一个退出值,脚本中可以用$?变量显示该值
使用原则:
1、函数一结束就取返回值,因为s?变量只返回执行的最后一条命令的退出状态码
2、退出状态码必须是0-255,超出时值将除以256取余
#!/bin/bash
function db1 {
read -p "please enter:" value
return $[$value * 2]
}
db1
echo $?

#!/bin/bash
db1() {
read -p "please enter:" value
echo $[$value * 2]
}
result=`db1`
echo $result

函数传参
#!/bin/bash
sum1() {
sum=$[$1 + $2]
echo $sum
}
read -p "enter the first parameter:" first
read -p "enter the second parameter:" second
sum1 $first $second

#!/bin/bash
sum2() {
sum=$[$1 + $2]
echo $sum
}
sum2 $1 $2

函数变量的作用范围:
-
函数在Shell脚本中仅在当前Shell环境中有效
-
Shell脚本中变量默认全局有效
-
将变量限定在函数内部使用local命令
#!/bin/bash
myfun() {
local i
i=8
echo $i
}
i=9
myfun
echo $i

递归
- 函数调用自己本身的函数
阶乘
#!/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 "please enter:" n
result=$(fact $n)
echo $result

递归目录
mkdir -p /root/bin/aa/bb/cc/dd ; touch /root/bin/aa/bb/cc/dd/abc.txt,
输出环境变量PATH所包含的所有目录以及其中的子目录和所有不可执行文件
#!/bin/bash
list_files() {
for i in $(ls $1)
do
if [ -d "$1/$i" ];then
echo "$2$i"
list_files "$1/$i" " $2"
else
if [ ! -x "$1/$i" ];then
echo "$2$i"
fi
fi
done
}
OLDIFS=$IFS
IFS=$IFS':'
for folder in $PATH
do
echo $folder
list_files "$folder" " "
done
IFS=$OLDIFS

函数库
vim myfuncs.sh
#!/bin/bash
fact() {
if [ $1 -eq 1 -o $1 -eq 0 ];then
echo 1
else
local temp=$[$1 - 1]
local result=$(fact $temp)
echo $[$1 * $result]
fi
}
add() {
echo $[$1 + $2]
}
sub() {
echo $[$1 - $2]
}
mult() {
echo $[$1 * $2]
}
div() {
if [ $2 -ne 0 ];then
echo $[$1 / $2]
else
echo "The dividend cannot be 0"
fi
}
vim testfuncs.sh
. myfuncs.sh v1=$1 v2=$2 res1=$(add $v1 $v2) res2=$(sub $v1 $v2) res3=$(mult $v1 $v2) res4=$(div $v1 $v2) res5=$(fact $v1) res6=$(fact $v2) echo "The result of addition is $res1" echo "The result of subtraction is $res2" echo "The result of multiplication is $res3" echo "The result of division is $res4" echo "$1 factorial is $res5" echo "$2 factorial is $res6"

浙公网安备 33010602011771号