You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
function func1{
echo "this is an example of a function"
}
count=1
while [ $count -le 5 ]
do
func1
count=$[ $count + 1 ]
done
echo "this is end of the loop"
func1
echo "now this is the end of the script"
function func1{
local temp=$[ $value + 5 ]
result=$[ $temp * 2 ]
}
temp=5
value=6
func1
echo "the result is $result"
if [ $temp -gt $value ]
then
echo "temp us larger"
else
echo "temp is smaller"
fi
在func1函数中使用$temp变量时,并不影响在脚本主体中赋给$temp变量的值;
数组变量和函数
向函数传数组参数
将数组变量当作单个参数传递的话,他不会起作用:如:
function test{
echo "the parameters are:$@"
thisarray=$1
echo "the received array is ${thisarray[*]}"
}
myarray=(1 2 3 4 5)
echo "the original array is : ${thisarray[*]}"
test $myarray
function fun1{
local newarray
newarray=($@)
echo "the new array value is : ${newarray[*]}"
}
myarray=(1 2 3 4 5)
echo "the original array is ${myarray[*]}"
fun1 ${myarray[*]}
正确的将数组参数传递给函数
function addarray{
local sum = 0
local newarray
newarray=($(echo "$@"))
for value in ${newarray[*]}
do
sum=$[ $sum + $value ]
done
echo $sum
}
myarray=(1 2 3 4 5)
echo "the original array is :${myarray[*]}"
arg1=$(echo ${myarray[*]})
result=$(addarray $arg1)
echo "the result is $result"
从函数返回数组
function arraydblr{
local origarray
local newarray
local elements
local i
origarray=($(echo "$@"))
newarray=($(echo "$@"))
elements=$[ $# - 1 ]
for(( i=1;i<=elements;i++)){
newarray[$i] = $[ ${origarray[$i]} * 2 ]
}
echo ${newarray[*]}
}
myarray=(1 2 3 4 5)
echo "the original array is : ${myarray[*]}"
arg1=$(echo ${myarray[*]})
result=($(arraydblr $arg1))
echo "the new array is : ${result[*]}"
函数可以调用自己来得到结果,通常递归函数都有一个最终可以迭代到的基准值;使用递归实现:X! = X * ( X - 1 )!计算阶乘;
function fun1{
if [$1 -eq 1 ]
then
echo 1
else
local temp=$[ $1 - 1 ]
local result=$(fun1 $temp)
echo $[ $result * $1 ]
fi
}
read -p "enter value:" value
result=$(fun1 $value)
echo "the fun1 of $value is : $result"