linux shell script 进阶篇(1)--如何打造功能强大的函数

函数不管在那个编程语言中都有举足轻重的地位,在linux shell script中当然也不例外,下面我们就一起学习如何打造出功能强大的函数。

1.如何在script中创建一个函数,可以用以下两种方式:

A.  function name

{

  commands

}

B.  name()

{

  commands

}

你只需要挑选上面的一种喜欢的方式来实现你的函数即可。

2.如何使用函数?我们通过一个例子来理解:

  1. $ cat test1  
  2. #!/bin/bash   
  3. # using a function in a script   
  4. function func1 {  
  5. echo "This is an example of a function"   
  6. }    #这里创建了我们自己的函数   
  7. count=1   
  8. while  [ $count -le  5  ]  #此处实现调用函数n次,n=5   
  9. do  
  10. func1  #这里调用我们创建的函数,就像使用命令一样。   
  11. count=$[ $count + 1  ]  
  12. done  
  13. echo "This is the end of the loop"   
  14. func1  
  15. echo "Now this is the end of the script"   
  16. $ ./test1  
  17. This is  an example of a function  
  18. This is  an example of a function  
  19. This is  an example of a function  
  20. This is  an example of a function  
  21. This is  an example of a function  
  22. This is  the end of the loop  
  23. This is  an example of a function  
  24. Now this is  the end of the script  
  25. $  

当然这里需要大家注意,如果你试图在函数创建之前使用它会提示错误。 command not found.我们看下面的例子:

  1. $ cat test2  
  2. #!/bin/bash   
  3. # using a function located in the middle of a script   
  4. count=1   
  5. echo "This line comes before the function definition"   
  6. function func1 {  
  7. echo "This is an example of a function"   
  8. }  
  9. while  [ $count -le  5  ]  
  10. do  
  11. func1  
  12. count=$[ $count + 1  ]  
  13. done  
  14. echo "This is the end of the loop"   
  15. func2  #在调用func2之前,函数还没有被创建,所以会报错。   
  16. echo "Now this is the end of the script"   
  17. function func2 {  
  18. echo "This is an example of a function"   
  19. }  
  20. $ ./test2  
  21. This line comes before the function definition  
  22. This is  an example of a function  
  23. This is  an example of a function  
  24. This is  an example of a function  
  25. This is  an example of a function  
  26. This is  an example of a function  
  27. This is  the end of the loop  
  28. ./test2: func2: command not  found  
  29. Now this is  the end of the script  
  30. $  

还有一个需要注意的是,你必须保证每一个函数名称都是唯一的, 否则会发生你意想不到的问题,我们通过下面的例子:

  1. $ cat test3  
  2. #!/bin/bash   
  3. # testing using a duplicate function name   
  4. function func1 {  
  5. echo "This is the first definition of the function name"   
  6. }   #这里定义了一个func1   
  7. func1  
  8. function func1 {  
  9. echo "This is a repeat of the same function name"   
  10. }   #这里出现了重复的定义func1   
  11. func1  #以后只要是调用函数func1的地方,都会调用第二次的定义。   
  12. echo "This is the end of the script"   
  13. $ ./test3  
  14. This is  the first definition of the function name  
  15. This is  a repeat of the same function name  
  16. This is  the end of the script  
  17. $  

3.函数的返回值,请看下面的例子:

A.当函数没有明确定义返回值时,默认返回值是函数最后一条命令的执行返回值。

  1. $ cat test4  
  2. #!/bin/bash   
  3. # testing the exit status of a function   
  4. func1() {  
  5. echo "trying to display a non-existent file"   
  6. ls -l badfile  
  7. }  #此函数没有明确定义返回值,因此它的返回值就是最后一条命令执行后的返回值。   
  8. echo "testing the function:"   
  9. func1  
  10. echo "The exit status is: $?"   
  11. $ ./test4  
  12. testing the function:  
  13. trying to display a non-existent file  
  14. ls: badfile: No such file or  directory  
  15. The exit status is1    #因为badfile不存在,所以ls命令返回1   
  16. $  

B.我们可以通过return命令自己指定想要返回的值,但是这个返回值是有条件的,它必须是0-255之间的整数,如果不在此范围,将会自动返回一错误值,大家可以调式下面的例子:

  1. $ cat test5  
  2. #!/bin/bash   
  3. # using the return command in a function   
  4. function dbl {  
  5. read -p "Enter a value: "  value  
  6. echo "doubling the value"   
  7. return  $[ $value * 2 ]  #这里是你指定的返回值,这个值是通过你输入的value值乘以2得到的,但它仍然要在0-255之间,否则返回错误值。(如何返回大于255的值我们后面会讲到)  
  8. }  
  9. dbl  
  10. echo "The new value is $?"   
  11. $ ./test5  
  12. Enter a value: 200   #这里value=200  
  13. doubling the value  
  14. The new  value  is  1   #需要返回的值为400,大于255,所以返回一错误值。但这个错误值不一定是1。  

请大家注意,既然return 能够主动从函数返回,所以return后面的语句将不被执行,你就别白费了。

4.使用函数的输出,你能够用一个脚本变量捕获函数的输出,就像捕获命令的输出一样,使用下面的语法:

result = `func1`  #func1函数中的所有输出都将定向到result变量。请看下面的例子:

 

  1. $ cat test5b  
  2. #!/bin/bash   
  3. # using the echo to return a value   
  4. function dbl {  
  5. read -p "Enter a value: "  value  
  6. echo $[ $value * 2  ]  
  7. }  
  8. result=`dbl`  
  9. echo "The new value is $result"   
  10. $ ./test5b  
  11. Enter a value: 200   
  12. The new value is   400    #这里得到了函数大于255的返回值哦,-_-   
  13. $ ./test5b  
  14. Enter a value: 1000   
  15. The new value is   2000   
  16. $  

5.如果你觉得上面的都懂了,那恭喜你,你已经有相当的功底了,我们继续往下看。

   如何在函数中使用变量:

A.  我们可以通过参数传递给函数传递变量,就像给脚本传递参数一样,函数中使用参数也和脚本中一样,我们可以使用$1,$2,$3...得到参数值,可以通过$#得到参数个数,可以通过$*或$@得到所有的参数内容。我们通过下面的例子来理解:

  1. $ cat test6  
  2. #!/bin/bash   
  3. # passing parameters to a function   
  4. function addem {  
  5. if  [ $ # -eq 0 ] || [ $# -gt 2 ]   
  6. then  
  7. echo -1   
  8. elif  [ $ # -eq 1 ]   
  9. then  
  10. echo $[ $1  + $ 1  ]  
  11. else   
  12. echo $[ $1  + $ 2  ]  
  13. fi  
  14. }  
  15. echo -n "Adding 10 and 15: "   
  16. value=`addem 10   15 `  
  17. echo $value  
  18. echo -n "Let’s try adding just one number: "   
  19. value=`addem 10 `  
  20. echo $value  
  21. echo -n "Now trying adding no numbers: "   
  22. value=`addem`  
  23. echo $value  
  24. echo -n "Finally, try adding three numbers: "   
  25. value=`addem 10   15   20 `  
  26. echo $value  
  27. $ ./test6  
  28. Adding 10   and   1525   
  29. Let’s try  adding just one number:  20   
  30. Now trying adding no numbers: -1   
  31. Finally, try  adding three numbers: - 1   
  32. $  

B. 学会使用全局变量与局部变量:

    B1.你可以在脚本的任何地方定义全局变量,包括函数中,使用变量定义的语法即可:

         variable=variable_value

    B2.任何在函数内部使用的变量你都可以定义为局部变量,使用下面的语法即可:

         local  local_variable=variable_value

使用局部定义创建的局部变量只能在定义的函数内使用。我们看下面的例子:

  1. $ cat test9  
  2. #!/bin/bash   
  3. # demonstrating the local keyword   
  4. function func1 {  
  5. local temp=$[ $value + 5  ]  
  6. result=$[ $temp * 2  ]  
  7. }  
  8. temp=4   
  9. value=6   
  10. func1  
  11. echo "The result is $result"   
  12. if  [ $temp -gt $value ]   #此处使用的temp的值将不会与函数和func1中的temp有任何关系。   
  13. then  
  14. echo "temp is larger"   
  15. else   
  16. echo "temp is smaller"   
  17. fi  
  18. $ ./test9  
  19. The result is   22   
  20. temp is  smaller  
  21. $  

C.如何给函数传递数组参数,这是需要艺术的。

   C1.如果你像传递单个参数那样给脚本传递数组,那么他将无法运行。看下面的例子:

  1. $ cat badtest3  
  2. #!/bin/bash   
  3. # trying to pass an array variable   
  4. function testit {  
  5. echo "The parameters are: $@"   
  6. thisarray=$1   
  7. echo "The received array is ${thisarray[*]}"   
  8. }  
  9. myarray=(1   2   3   4   5 )  
  10. echo "The original array is: ${myarray[*]}"   
  11. testit $myarray  
  12. $ ./badtest3  
  13. The original array is1   2   3   4   5   
  14. The parameters are: 1   
  15. ./badtest3: thisarray[*]: bad array subscript  #也许你没有产生这个错误,但是我要说,你也只能获得数组的第一个值。   
  16. The received array is   
  17. $  

C2.解决这个问题的方法是,我们可以把数组拆开成每个值,然后作为函数的参数值传递给函数,最后在函数内部我们把它再组合成数组使用。也许你觉得这个根本就是个笨的办法。但我们还是可以试试,看下面的例子:

  1. $ cat test10  
  2. #!/bin/bash   
  3. # array variable to function test   
  4. function testit {  
  5. local newarray  
  6. newarray=(`echo "$@" `)  #这里把函数的所有参数组合成一个数组。   
  7. echo "The new array value is: ${newarray[*]}"   
  8. }  
  9. myarray=(1   2   3   4   5 )  
  10. echo "The original array is ${myarray[*]}"   
  11. testit ${myarray[*]} #这里我们把数组的每一个值都作为参数传递给了函数。   
  12. $ ./test10  
  13. The original array is   1   2   3   4   5   
  14. The new array value is1   2   3   4   5   
  15. $  

我们再看一个使用数组的例子,最好是练习它:

  1. $ cat test11  
  2. #!/bin/bash   
  3. # adding values in an array   
  4. function addarray {  
  5. local sum=0   
  6. local newarray  
  7. newarray=(`echo "$@" `)  
  8. for  value  in  ${newarray[*]}  
  9. do  
  10. sum=$[ $sum + $value ]  
  11. done  
  12. echo $sum  
  13. }  
  14. myarray=(1   2   3   4   5 )  
  15. echo "The original array is: ${myarray[*]}"   
  16. arg1=`echo ${myarray[*]}`  
  17. result=`addarray $arg1`  
  18. echo "The result is $result"   
  19. $ ./test11  
  20. The original array is1   2   3   4   5   
  21. The result is   15   
  22. $  

C3.如何返回一个数组,我们还是借用上面传递类似的方法,请看下面的例子:

  1. $ cat test12  
  2. #!/bin/bash   
  3. # returning an array value   
  4. function arraydblr {  
  5. local origarray  
  6. local newarray  
  7. local elements  
  8. local i  
  9. origarray=(`echo "$@" `)  
  10. newarray=(`echo "$@" `)  
  11. elements=$[ $# - 1 ]   
  12. for  (( i =  0 ; i <= $elements; i++ ))  
  13. {  
  14. newarray[$i]=$[ ${origarray[$i]} * 2  ]  
  15. }  
  16. echo ${newarray[*]}  
  17. }  
  18. myarray=(1   2   3   4   5 )  
  19. echo "The original array is: ${myarray[*]}"   
  20. arg1=`echo ${myarray[*]}`  
  21. result=(`arraydblr $arg1`) #这里把函数的输出结果重新组合成数组   
  22. echo "The new array is: ${result[*]}"   
  23. $ ./test12  
  24. The original array is1   2   3   4   5   
  25. The new array is2   4   6   8   10   

6.函数的递归操作,这种迭代操作一般都是基于一种存在情况,并且这种情况有特定的值。看下面的例子:

  1. $ cat test13  
  2. #!/bin/bash   
  3. # using recursion   
  4. function factorial {  
  5. if  [ $ 1  -eq  1  ]  
  6. then  
  7. echo 1   
  8. else   
  9. local temp=$[ $1  -  1  ]  
  10. local result=`factorial $temp`  #此处进行迭代计算   
  11. echo $[ $result * $1  ]  
  12. fi  
  13. }  
  14. read -p "Enter value: "  value  
  15. result=`factorial $value`  
  16. echo "The factorial of $value is: $result"   
  17. $ ./test13  
  18. Enter value: 5   
  19. The factorial of 5   is120   
  20. $  

7.最后跟大家一起分享的是,创建自己的libary简化自己的脚本编写。

   大家可以把自己经常使用的一些函数编写到一个固定的脚本中,然后在需要此中的函数时就先引用这个文件即可。

请用下面的语法引用:

   ../mylibary

示例:

  1. $ cat myfuncs  
  2. # my script functions   
  3. function addem {  
  4. echo $[ $1 + $2 ]  
  5. }  
  6. function multem {  
  7. echo $[ $1 * $2 ]  
  8. }  
  9. function divem {  
  10. if  [ $2 -ne 0 ]  
  11. then  
  12. echo $[ $1 / $2 ]  
  13. else   
  14. echo -1  
  15. fi  
  16. #下面新建一个脚本使用上面的函数   
  17. $ cat test14  
  18. #!/bin/bash   
  19. # using functions defined in a library file   
  20. . ./myfuncs  
  21. value1=10  
  22. value2=5  
  23. result1=`addem $value1 $value2`  
  24. result2=`multem $value1 $value2`  
  25. result3=`divem $value1 $value2`  
  26. echo "The result of adding them is: $result1"   
  27. echo "The result of multiplying them is: $result2"   
  28. echo "The result of dividing them is: $result3"   
  29. $ ./test14  
  30. The result of adding them is : 15  
  31. }  #创建了一个含有需要函数的脚本作为libary  
  32. $  

以上是我学习的一些笔记,希望跟大家一起分享探讨。

 

from http://blog.csdn.net/wesleyluo/archive/2010/02/08/5297558.aspx

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值