高级shell脚本编程(一)函数

引文: 通常编写shell脚本时,你会发现很多地方都要用到相同的代码或者说是相同的功能。如果是一段小代码,那无所谓。可如果多次使用而且还是相同的代码,我想你也会感觉很烦的。为了能够让代码重用,这就使用到函数了。

温馨提示 变量赋值的格式为:

变量名=变量值

注意事项:

函数定义格式function name {commands}

或者是

name() {}

这个就和其他的语言有点类似了。

实例1.无参函数

一个简单的使用函数功能的shell脚本 test1.sh

#!/bin/bash# this is a test file for test functionfunction func1 {echo “this is an example of function!”}count=.”while [ $count -le 5 ]dofunc1count = $[ $count + 1 ]

运行:

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.

实例2.带参函数

test2.sh

#!/bin/bash# this is a test file for test functionfunction addem {] || [ ][ ]thenecho $[ $1 + $1]elseecho $[ $1 + $2 ]fi}echo -n “Adding 10 and 5:”value=`addem 10 15`-n “Let’s try adding just one number:”value=`addem 10`-n “Now trying adding no number:”value=`addem`-n “Finally,we try adding three numbers:”value=`addem `

测试:

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。

实例3.数组参数

test3.sh

#!/bin/bash# trying to pass a array variablefunction testit {local newarray # use ‘local’ define a local variablenewarray=(`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

实例4.函数递归

定义阶乘函数x! = x * (x-1)

function factorial {]local temp=$[ $1 – 1 ]local result=`factorial $temp`echo $[$result * $1]fi}

详细实例:test4.py

#!/bin/bash# using recursionfunction factorial {]local temp=$[ $1 – 1 ]local result=`factorial $temp`echo $[ $result * $1 ]fi}

测试:

sh test4.py

输出: Enter value:6 The factorial of 6 is: 720

实例5.命令行上使用函数命令[root@master chapter16]# function multm {> echo $[ $1 * $2 ]> }[root@master chapter16]# multm 2 510

注意: 在命令行上定义函数时,如果你给函数起的名字跟内建命令or另一个命令相同名字,则函数将覆盖原来的命令。

如果想要开机生效,可以把函数卸载/etc/.bashrc文件中。

只是微笑地固执自己的坚持,

高级shell脚本编程(一)函数

相关文章:

你感兴趣的文章:

标签云: