SHELL中的函数
1. 语法
方法1:
函数名() {
函数体
return n
}
方法2:
function 函数名() {
函数体
return n
}
2. 调用函数
#!/bin/bash
function fun1() {
echo "I like westos"
}
fun1 ##调用函数
3. 引用函数
- 每次引用函数时,bash会重新回到函数的定义
[root@server ~]# cat function.sh
#!/bin/bash
function fun1() {
echo "I am a boy~"
}
count=1
while [ $count -le 5 ]
do
fun1
count=$[ $count + 1 ]
done
echo "End of loop"
fun1
echo "End of script"
[root@server ~]# sh function.sh
I am a boy~
I am a boy~
I am a boy~
I am a boy~
I am a boy~
End of loop
I am a boy~
End of script
4. 函数不一定要在最开始定义,但是如果函数在定义前就使用,会报错
[root@server ~]# cat function.sh
fun2
function fun2() {
echo "fun2"
}
[root@server ~]# sh function.sh
function.sh: line 1: fun2: command not found
5. 函数名必须是唯一的,如果重新定义了函数,新的函数会覆盖旧的
[root@server ~]# cat exit_01.sh
#!/bin/bash
function fun1() {
echo "trying to display a non-existent file"
ls -l westosfile &> /dev/null
}
echo "test the function:"
fun1
echo "The exit status is : $?"
[root@server ~]# sh exit_01.sh
test the function:
trying to display a non-existent file
The exit status is : 2
[root@server ~]# cat exit_02.sh
#!/bin/bash
function fun1() {
ls -l westosfile &> /dev/null
echo "trying to display a non-existent file"
}
echo "test the function:"
fun1
echo "The exit status is : $?"
[root@server ~]# sh exit_02.sh
test the function:
trying to display a non-existent file
The exit status is : 0
6. 返回值
1)默认退出状态码:默认情况下,函数的退出状态码是函数中最后一条命令返回的退出状态码
2)使用return命令
shell使用return命令来退出函数并返回特定的退出状态码
[root@server ~]# cat return.sh
#!/bin/bash
function db1() {
read -p "Enter a value:" value
echo "doubling the value..."
return $[ $value * 2 ]
}
db1
echo "The new value is $?"
[root@server ~]# sh return.sh
Enter a value:6
doubling the value...
The new value is 12
3)使用函数输出
- 将函数的输出保存在shell变量中,可以获得任何类型的函数输出,并将其保存到变量中
[root@server ~]# cat result.sh
#!/bin/bash
function db1() {
read -p "Enter a value:" value
echo $[ $value * 2 ]
}
result=`db1`
echo "The new value is $result"
[root@server ~]# sh result.sh
Enter a value:3
The new value is 6
4)函数中使用变量
- 可以向函数中传递参数函数名会在
$0
变量中定义,函数命令行上的任何参数都会通过$1
,$2
定义,$#
来判断传给函数的参数数目
5)函数不能直接从命令行获取脚本的参数值
[root@server ~]# cat fun1
cat: fun1: No such file or directory
[root@server ~]# cat fun1.sh
function fun1() {
echo $[ $1 * $2 ]
}
if [ $# -eq 2 ];then
value=`fun1`
echo "The result is $value"
else
echo "Usage:fun1 a b"
fi
[root@server ~]# sh fun1.sh 2 3
fun1.sh: line 2: * : syntax error: operand expected (error token is "* ")
The result is
[root@server ~]# vim fun1.sh
[root@server ~]# cat fun1.sh
function fun1() {
echo $[ $1 * $2 ]
}
if [ $# -eq 2 ];then
value=`fun1 $1 $2`
echo "The result is $value"
else
echo "Usage:fun1 a b"
fi
[root@server ~]# sh fun1.sh 2 3
The result is 6