引文: 通常编写shell脚本时,你会发现很多地方都要用到相同的代码或者说是相同的功能。如果是一段小代码,那无所谓。可如果多次使用而且还是相同的代码,我想你也会感觉很烦的。为了能够让代码重用,这就使用到函数了。
温馨提示
变量赋值的格式为:
变量名=变量值
注意事项:
function name {
commands
}
或者是
name() {
}
这个就和其他的语言有点类似了。
一个简单的使用函数功能的shell脚本
test1.sh
#!/bin/bash
# this is a test file for test function
function func1 {
echo "this is an example of function!"
}
count=1
echo "count‘s value is $count."
while [ $count -le 5 ]
do
func1
count = $[ $count + 1 ]
done
echo "end of while."
运行:
sh test1.sh
输出:
count’s value is 1.
this is an example of function!
this is an example of function!
this is an example of function!
this is an example of function!
this is an example of function!
end of while.
test2.sh
#!/bin/bash
# this is a test file for test 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 5:"
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,we try adding three numbers:"
value=`addem 10 15 20`
echo $value
echo "end of file."
测试:
sh test2.sh
输出:
Adding 10 and 5:25
Let’s try adding just one number:20
Now trying adding no number:-1
Finally,we try adding three numbers:-1
end of file.
如果想在函数内部声明一个变量,可以使用local来定义,表示为局部变量。如local temp=1
。
test3.sh
#!/bin/bash
# trying to pass a array variable
function testit {
local newarray # use ‘local’ define a local variable
newarray=(`echo "$@"`)
echo "the newarray value is ${newarray[*]}"
}
myarray=(1,2,3,4,5)
echo "the original array is:${myarray[*]}"
testit $myarray
测试:
sh test3.sh
输出:
the original array is:1,2,3,4,5
the newarray value is 1,2,3,4,5
定义阶乘函数x! = x * (x-1)
function factorial {
if [ $1 -eq 1 ]
then
echo 1
else
local temp=$[ $1 - 1 ]
local result=`factorial $temp`
echo $[$result * $1]
fi
}
详细实例:test4.py
#!/bin/bash
# using recursion
function factorial {
if [ $1 -eq 1 ]
then
echo 1
else
local temp=$[ $1 - 1 ]
local result=`factorial $temp`
echo $[ $result * $1 ]
fi
}
测试:
sh test4.py
输出:
Enter value:6
The factorial of 6 is: 720
[root@master chapter16]# function multm {
> echo $[ $1 * $2 ]
> }
[root@master chapter16]# multm 2 5
10
注意: 在命令行上定义函数时,如果你给函数起的名字跟内建命令or另一个命令相同名字,则函数将覆盖原来的命令。
如果想要开机生效,可以把函数卸载/etc/.bashrc文件中。
原文地址:http://blog.csdn.net/dream_angel_z/article/details/45917431