shell函数的定义,返回值和参数

一、函数的定义
shell允许将一组命令集或语句形成一个可用的块,这些块称为shell函数;
定义的格式:
functionName(){
command1
command2
......
commandN
[ return value]
}
function functionName(){    # function为关键字
command1
command2
......
commandN
[ return value]
}

二、函数参数$n(1...),其中$0不论什么时候都表示文件名

#!/bin/bash
funcWithReturn(){
	echo "The function is to get the sum of two numbers..."
	echo -n "Input first number:"
	read aNum
	echo -n "Input another number:"
	read bNum
	echo "The tow numbers are $aNum and $bNum !"
	return $(($aNum+$bNum))
}
funcWithReturn
echo "The sum of tow numbers is $? " # $?上个命令退出的状态,或函数返回结果

function funcWithParam(){
echo "The value of the first parameter is $1 "
echo "The value of the third parameter is $3 "
echo "The value of the tenth parameter is $10 "
echo "The value of the tenth parameter is ${10} "
echo "The value of the eleventh parameter is ${11} "
echo "The amount of the parameters is $# "
echo "The string of the parameters is $* "
echo "The value of \$0: $0"
}
funcWithParam 1 2 3 4 5 6 7 8 9 10 88 66  #使用空格将参数分割开	
执行结果

hyc@hyc-csu:~/shellCommands$ bash funcwithreturn.sh
The function is to get the sum of two numbers...
Input first number:90
Input another number:9
The tow numbers are 90 and 9  
The sum of tow numbers is 99  
The value of the first parameter is 1
The value of the third parameter is 3
The value of the tenth parameter is 10
The value of the tenth parameter is 10
The value of the eleventh parameter is 88
The amount of the parameters is 12
The string of the parameters is 1 2 3 4 5 6 7 8 9 10 88 66
the value of $0: funcwithreturn.sh

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值