shell编程之自定义函数

本文介绍了Shell脚本中函数的基本语法,包括定义和调用函数的方法。强调了函数声明的位置和返回值的处理方式,通过示例展示了如何使用函数进行简单的数学运算。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.基本语法

[ function ] funname[()]

{

Action;

[return int;]

}

funname

2.经验技巧

(1)必须在调用函数地方之前,先声明函数,shell脚本是逐行运行。不会像其它语言一样先编译。

(2)函数返回值,只能通过$?系统变量获得,可以显示加:return返回,如果不加,将以最后一条命令运行结果,作为返回值。return后跟数值n(0-255)

3.示例

[root@eshop-detail03 shell]# vi fun.sh
#!/bin/bash
function sum()
{
    s=0
    s=$[ $1 + $2 ]
    echo "$s"
}

read -p "Please input the number1: " n1;
read -p "Please input the number2: " n2;
sum $n1 $n2;
~
~
"fun.sh" [New] 11L, 168C written
[root@eshop-detail03 shell]# chmod 777 fun.sh
[root@eshop-detail03 shell]# ./fun.sh
Please input the number1: 8
Please input the number2: 10
18
[root@eshop-detail03 shell]# ./fun.sh
Please input the number1: 258
Please input the number2: 2
260

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值