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

你可能感兴趣的:(ubuntu/linux,shell)