Shell脚本(五)函数

大憨熊 提交于 2020-02-05 12:09:19

总结下shell中的函数用法

#!/bin/bash

function add_v1() {
    echo "call function add"
}

function add_v2() {
    echo "number of params: $#"
    echo "first param: $1"
    echo "second param: $2"

    local sum=0
    for item in $@
    do
        sum=$(($sum + $item))
    done
    echo "result is $sum"
}

function add_v3() {
    local sum=0
    for item in $@
    do
        sum=$(($sum + $item))
    done
    
    return $sum
}

# another way to return value
function add_v4() {
    local sum=0
    for item in $@
    do
        sum=$(($sum + $item))
    done
    
    echo $sum
}

global_variable=0

function add_v5() {
    local sum=0
    for item in $@
    do
        sum=$(($sum + $item))
    done
    
    global_variable=$sum
}

add_v1

add_v2 10 20 30 

add_v3 10 20 30
# get return value from $?
# in this case, the max return value is 255, 256 will be 0
echo "return value of add_v3: $?"

# get return value directly
# in this case , no limit on return value
result_v4=`add_v4 200 50 5`
echo "return value of add_v4: $result_v4"

add_v5 100 200 300
echo "global_variable: $global_variable"

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!