shell脚本函数传参

函数可以提高代码复用,在python、java中比较常见。
shell脚本也有函数,可以将一组命令集或语句形成一个可用代码块。

定义格式
函数名(){
    command1
    command2
    ...
    commandN
    [ return value ]
}
函数返回值

可以显示增加return语句;如果不加,则将最后一条命令运行结果作为返回值(一般为0,如果执行失败则返回错误代码)。
return后跟数值(0-255)


#! /bin/bash

function test(){
        echo "The first param is $1"
        return 111
}

test 1
echo "The return of test is $?"

运行结果:

[root@master ~]# sh test_function.sh 
The first param is 1
The return of test is 111
Shell函数传参

在Shell中,调用函数时可以向其传递参数。在函数体内部,通过 $n 的形式来获取参数的值,例如,$1表示第一个参数,$2表示第二个参数…即使用位置参数来实现参数传递。

#! /bin/bash

function test(){
        echo "The first param is $1"
        echo "The second param is $2"
        echo "The third param is $3"
        echo "The forth param is $4"
        echo "The fifth param is $5"
        echo "The sixth param is $6"
        echo "The seventh param is $7"
        echo "The eigth param is $8"
        echo "The ninth param is $9"
        echo "The tength param is $10"
        echo "The 11th param is $11"
        return 111
}

test 1 2 3 4 5 6 7 8 9 55 54
echo "The return of test is $?"

运行结果:
[root@master ~]# sh test_function.sh
The first param is 1
The second param is 2
The third param is 3
The forth param is 4
The fifth param is 5
The sixth param is 6
The seventh param is 7
The eigth param is 8
The ninth param is 9
The tength param is 10
The 11th param is 11

注意,$10 不能获取第十个参数,如上结果中$10,打印结果为10。
获取第十个参数需要${10}。

正确姿势,当n>=10时,需要使用${n}来获取参数:

#! /bin/bash

function test(){
        echo "The first param is $1"
        echo "The second param is $2"
        echo "The third param is $3"
        echo "The forth param is $4"
        echo "The fifth param is $5"
        echo "The sixth param is $6"
        echo "The seventh param is $7"
        echo "The eigth param is $8"
        echo "The ninth param is $9"
    	echo "The tength param is ${10}"
    	echo "The 11th param is ${11}"
        return 111
}

test 1 2 3 4 5 6 7 8 9 55 54
echo "The return of test is $?"

运行结果:
[root@master ~]# sh test_function.sh
The first param is 1
The second param is 2
The third param is 3
The forth param is 4
The fifth param is 5
The sixth param is 6
The seventh param is 7
The eigth param is 8
The ninth param is 9
The tength param is 55
The 11th param is 54
The return of test is 111

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值