#!/bin/bash
sum=0 #全局变量
function getsum(){
for((i=$1; i<=$2; i++)); do
((sum+=i)) #改变全局变量
done
echo "--"
return $? #返回上一条命令的退出状态
}
read m
read n
getsum $m $n
echo "The sum is $sum" #输出全局变量
if getsum $m $n; then
echo "The sum is $sum" #输出全局变量
else
echo "Error!"
fi
脚本输出结果:
#!/bin/bash
sg=0
function f1()
{
sum=0
for((i=$1;i<=$2;i++))
do
((sum+=i))
done
sg=$sum
echo $sum
echo "__"
echo "f1_sum=$sum"
echo "---"
echo "f1_sg=$sg"
return $?
}
read a
read b
s=$(f1 $a $b) #$()可以捕获函数里面的第一个echo , 全局变量sg为0
echo "s=${s}" #s=__
#f1 $a $b #
echo $?
echo "sum=${sum}"
echo "sg is $sg"
脚本输出结果: