7 函数
shell函数格式:没有返回值类型+参数列表
格式:[function] 函数名[()]{
statement;
[return 返回值;]
}
7.1 函数中涉及的变量
function test1(){
echo '$0='$0;
echo '$*='$*;
echo '$@='$@;
echo '$#='$#;
echo '$1='$1;
echo '$2='$2;
echo '$$='$$;
}
test1 2 3 4 5 6;
7.2 练习
function add1(){
sumab=$(($1+$2));
return $sumab;
}
add1 3 4;
sum1=$?;
echo "3+4="$sum1;
function test2(){
geShu=1;
for i in $*;do
echo '第'$geShu'个参数的值是:'$i;
geShu=$((geShu+1));
done;
}
test2 2 9 7 1 6;
function pdZhiShu(){
if [ $1 -le 1 ]; then
return 1;
fi;
for ((m=2;m<$1;m++));do
if [ $(($1%m)) -eq 0 ];then
return 1;
fi;
done;
return 0;
}
for ((n=0;n<=10;n++));do
pdZhiShu $n;
result=$?;
if [ $result -eq 0 ];then
echo $n'是质数';
fi;
done;
function test3(){
days=0;
year=$1;month=$2;
case $month in
4 | 6 | 9 | 11)
days=30;;
2)
if [ $((year%4)) -eq 0 -a $((year%100)) -ne 0 -o $((year%400)) -eq 0 ];then
days=29;
else
days=28;
fi;;
*)
days=31;;
esac;
return $days;
}
for ((year=2000;year<=2020;year++));do
for ((month=1;month<=12;month++));do
test3 $year $month;
echo $year'年'$month'月有'$?'天!';
done;
done;
function heiDong(){
for ((n=1000;n<10000;n++));do
if [ $((n%1111)) -eq 0 ];then
continue;
fi;
k=$n;
ciShu=0;
while [ $k -ne 6174 ];do
arr=($((k%10)) $((k/10%10)) $((k/100%10)) $((k/1000)));
for ((i=0;i<${#arr[*]}-1;i++));do
for ((j=i+1;j<${#arr[*]};j++));do
if [ ${arr[i]} -gt ${arr[j]} ];then
temp=${arr[i]};arr[i]=${arr[j]};arr[j]=$temp;
fi;
done;
done;
maxArr=$((${arr[3]}*1000+${arr[2]}*100+${arr[1]}*10+${arr[0]}*1));
minArr=$((${arr[0]}*1000+${arr[1]}*100+${arr[2]}*10+${arr[3]}*1));
k=$((maxArr-minArr));
ciShu=$((ciShu+1));
done;
echo $n'经过'$ciShu'次运算后得到'$k;
done;
}
function fbnq1(){
arg=$1;
arr=(1 1);
for ((i=2;i<arg;i++));do
arr[$i]=$((${arr[i-1]}+${arr[i-2]}));
done;
echo ${arr[*]};
resultFbnq=${arr[arg-1]};
}
for ((n=1;n<=20;n++));do
fbnq1 $n;
echo '第'$n'个元素是:'$resultFbnq;
done;
7.3 注意return的作用
function test3(){
return 1597;
}
test3;echo '1597='$?;
function test4(){
result4=$(($1+1));
}
test4 3;
echo '3+1='$result4;