1.创建函数
function name {
commands
}
也可以写成下面这种形式
name() {
commands
}
2.函数返回值
函数退出状态是函数最后条命令返回的退出状态,可以用 $? 确定函数的退出状态
使用return:
#!/bin/bash
func1() {
read -p "Enter a value: " value
echo "the value times two"
return $[ $value * 2 ]
}
func1
echo "now value = $?"
使用函数的输出:
#!/bin/bash
func1() {
read -p "Enter a value: " value
echo $[ $value *2 ]
}
v1=`func1`
echo "v1 = $v1"
allen@ubuntu:~/learnlinux$ ./read.sh
Enter a value: 10
v1 = 20
3.在函数中使用变量
函数可以使用标准参数环境变量来表示命令行传递给函数的参数. 专用变量 $# 可以用来确定传递给函数的参数数目.
在脚本中指定函数时,必须在函数所在命令行提供参数 : func1 $value1 10
#!/bin/bash
# passing parameters to a function
function addem {
if [ $# -eq 0 ] || [ $# -gt 2 ]
then
echo -1
elif [ $# -eq 1 ]
then
echo $[ $1 + $1 ]
else
echo $[ $1 + $2 ]
fi
}
echo -n "Adding 10 and 15: "
value=`addem 10 15`
echo $value
echo -n "Let's try adding just one number: "
value=`addem 10`
echo $value
echo -n "Now trying adding no number: "
value=`addem`
echo $value
echo -n "Finally, try adding three numbers: "
value=`addem 10 15 20`
echo $value
allen@ubuntu:~/learnlinux/UNIX$ ./func.sh
Adding 10 and 15: 25
Let's try adding just one number: 20
Now trying adding no number: -1
Finally, try adding three numbers: -1