【shell】shell 函数

shell 函数

1.定义函数

方法一

函数名(){
    函数要实现的功能
}

方法二

function 函数名{
    函数要实现的功能
}

如果函数需要传递参数的的用$1,$2,局部变量定义用local,返回值的话return $?(最后一句执行成功情况)

2.实例

2.1 阶乘实例

[klaus@localhost chapt7]$ cat factor.sh
#!/bin/bash

factorial(){
    factor=1
    for(( i=1;i<=$1;i++ ))
    do
        #factor=$[$factor * $i]
        #let factor=$factor*$i
        let factor*=$i
    done
    echo "The factorial of $1 is $factor"
}

factorial $1
[klaus@localhost chapt7]$ ./factor.sh 5
The factorial of 5 is 120

2.2 函数返回值传递

这里的local表示局部变量,在当前阶段使用,理解同c语言的局部变量

[klaus@localhost chapt7]$ cat return.sh
#!/bin/bash
factorial(){
    local factor=1
    for(( i=1;i<=$1;i++  ))
    do
        let factor*=$i
    done
    echo "The factorial of $1 is $factor"
}

double_read(){
    read -p "please enter a num:" num
    echo $[2*$num]
}

result=`double_read`
factorial $result
[klaus@localhost chapt7]$ ./return.sh
please enter a num:3
The factorial of 6 is 720

shell里面,return的值不能超过255,而且只是整数,如果需要返回浮点数或者小数就不能使用return的方式,echo这个可以考虑一下。而且return的结果也不能直接赋值给某个变量,不能直接使用,查看return的值用$?

[klaus@localhost chapt7]$ cat test.sh
#!/bin/bash

test(){
    read -p "plese enter a num:" num
    return $[3*$num]
}
test
echo "test result return value is $?"
[klaus@localhost chapt7]$ ./test.sh
plese enter a num:100
test result return value is 44
[klaus@localhost chapt7]$ ./test.sh
plese enter a num:5
test result return value is 15

3.函数数组传递

同样先来看一下一个简单的数组内元素累乘的样例

[klaus@localhost chapt7]$ cat array_acc.sh
#!/bin/bash
num=(1 2 3 4 5)
#echo "all array num is ${num[@]}"

array(){
    local factor=1
    local i
    for i in "$@"
    do
        factor=$[$factor*$i]
    done
    echo "$factor"
}
result=`array ${num[@]}`
echo "result is $result"
[klaus@localhost chapt7]$ ./array_acc.sh
result is 120

函数接收的位置参数为$1,$2,$3,$4…
函数接收数组变量为 *或者 @
然后函数将接收到的所有参数赋值给数组,这样就能完成数组的调用,其中函数使用参数的个数用$#表示

[klaus@localhost chapt7]$ cat doubleArray.sh
#!/bin/bash
num=(1 2 3 4 5)
array(){
    echo "all parameters is $*"
    local newarray=($*)
    local i
    for(( i=0;i<$#;i++ ))
    do
        outarray[$i]=$[ newarray[$i]*2 ]
    done
    echo "${outarray[*]}"
}

result=`array ${num[*]}`
echo "${result[*]}"
[klaus@localhost chapt7]$ ./doubleArray.sh
all parameters is 1 2 3 4 5
2 4 6 8 10
发布了80 篇原创文章 · 获赞 86 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/klaus_x/article/details/104252284