Shell编程之函数使用

方法参数传递机制详解

函数介绍

函数在编程中作用不言而喻

函数定义

定义方式一:

name()
{
    command;
    command2;
}

定义方式二:

[ function ] funname [ () ]
{
    action1;
    [ return value; ]
}
函数案例一
#!/bin/bash

#声明外部变量
aa="this is aa"
bb="this is bb"

function test()
{
        #声明局部变量
        cc="this is cc"
        dd="this is dd"
        echo "$aa , $cc"
        echo "$bb"
        echo "$dd"
}

#函数调用
test

带有参数的方法调用

#!/bin/bash
aa="this is aa"
bb="this is bb"

function test()
{
        cc="this is cc"
        dd="this is dd"
        echo "$aa , $cc"
        echo "$bb"
        echo "$dd"

        echo $1
        echo "are you ok ? $2"
}

#函数调用
test 100 "hello,world"

100阶乘的实现

#!/bin/bash
a=1
function doJieCheng ()
{
        for i in `seq $1`
        do
                a=$[ $i * $a ]
                # let a*=$i
                # let a=$a*$i
        done

        echo "$1的阶乘 $a"
}

doJieCheng $1

带有返回值的函数

#!/bin/bash

sum(){
        echo $[ $1+$2 ] #最后一条语句的执行结果,就是返回值
        #return 只能返回0-255之间的数值,且不能终止该方法的执行
}

sum $1 $2



!/bin/bash
  
sum(){
        echo $[ $1+$2 ]
}

result=`sum 1 2`

echo $result
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值