Bash脚本编程指北(7)函数

函数

函数定义

shell 中函数的定义格式如下:

[ function ] funname [()]

{

    action;

    [return int;]

}
  • 说明:

可以带 function fun() 定义,也可以直接 fun() 定义,不带任何参数。

参数返回,可以加return 返回,如果不加,将以最后一条命令运行结果,作为返回值。 return 后跟数值 n(0-255)

下面的例子定义了一个函数并进行调用:

#!/bin/bash

demoFun(){
    echo "This is my first shell function!"
}
echo "-----Execution-----"
demoFun
echo "-----Finished-----"


Output the result:
-----Execution-----
This is my first shell function!
-----Finished-----

下面定义一个带有 return 语句的函数:

#!/bin/bash
funWithReturn(){
    echo "This function will add the two numbers of the input..."
    echo "Enter the first number: "
    read aNum
    echo "Enter the second number: "
    read anotherNum
    echo "The two numbers are $aNum and $anotherNum !"
    return $(($aNum+$anotherNum))
}
funWithReturn
echo "The sum of the two numbers entered is $? !"

输出类似下面:

This function will add the two numbers of the input...
Enter the first number:
1
Enter the second number:
2
The two numbers are 1 and  2 !
The sum of the two numbers entered is 3 !

函数返回值在调用该函数后通过 $? 来获得,所有函数在使用前必须定义。

函数参数

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

带参数的函数示例:

#!/bin/bash
funWithParam(){
    echo "The first parameter is $1 !"
    echo "The second parameter is $2 !"
    echo "The tenth parameter is $10 !"
    echo "The tenth parameter is ${10} !"
    echo "The eleventh parameter is ${11} !"
    echo "The total number of parameters is $# !"
    echo "Outputs all parameters as a string $* !"
}
funWithParam 1 2 3 4 5 6 7 8 9 34 73

输出结果:

The first parameter is 1 !
The second parameter is 2 !
The tenth parameter is 10 !
The tenth parameter is 34 !
The eleventh parameter is 73 !
The total number of parameters is 11 !
Outputs all parameters as a string 1 2 3 4 5 6 7 8 9 34 73 !

注意:$10 不能获取第十个参数,获取第十个参数需要 ${10}。当 n>=10 时,需要使用 ${n} 来获取参数。

命令解释
$#传递到脚本的参数个数
$*以一个单字符串显示所有向脚本传递的参数。与位置变量不同,此选项参数可超过 9 个
$$脚本运行的当前进程 ID 号
$!后台运行的最后一个进程的进程 ID 号
$@与 $* 相同,但是使用时加引号,并在引号中返回每个参数
$显示 shell 使用的当前选项,与 set 命令功能相同
$?显示最后命令的退出状态。 0 表示没有错误,其他任何值表明有错误。
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

海岸星的清风

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值