shell 教程六:函数的使用

来源:互联网 发布:淘宝全屏店招导航 编辑:程序博客网 时间:2024/06/03 09:07

1,函数无参无返回值调用

  1. linux@ubuntu:~/test_shell$ cat hello.sh
  2. #!/bin/bash
  3. myFunc(){
  4. echo "myFunc() is called!"
  5. }
  6. echo "begin call myFunc()"
  7. myFunc
  8. echo "end call myFunc()"
  9. linux@ubuntu:~/test_shell$ ./hello.sh
  10. begin call myFunc()
  11. myFunc() is called!
  12. end call myFunc()

2,函数无参有返回值调用

  1. linux@ubuntu:~/test_shell$ cat hello.sh
  2. #!/bin/bash
  3. myFunc(){
  4. echo "myFunc() is called!"
  5. a=1;
  6. b=2;
  7. return $(($a+$b))
  8. }
  9. echo "begin call myFunc()"
  10. myFunc
  11. echo "myFunc() return $?"
  12. echo "end call myFunc()" # 13行与14行代码不能互换,应该echo也是一种函数
  13. linux@ubuntu:~/test_shell$ ./hello.sh
  14. begin call myFunc()
  15. myFunc() is called!
  16. myFunc() return 3
  17. end call myFunc()

注意:所有函数在使用前必须定义。这意味着必须将函数放在脚本开始部分,直至shell解释器首次发现它时,才可以使用。调用函数仅使用其函数名即可。
函数返回值在调用该函数后通过 $? 来获得。

3,函数使用参数

  1. linux@ubuntu:~/test_shell$ cat hello.sh
  2. #!/bin/bash
  3. myFunc(){
  4. echo "=====myFunc()===="
  5. echo "$1"
  6. echo "$2"
  7. echo "$3"
  8. echo "$4"
  9. echo "$5"
  10. echo "$6"
  11. echo "$7"
  12. echo "$8"
  13. echo "$9"
  14. echo "${10}" # $10以上的应该要加{},着色也提示了,1与0的颜色不一样,但实测ubuntu是能用的
  15. echo "${11}"
  16. echo "$*"
  17. echo "=====myFunc()===="
  18. a=3
  19. return $a
  20. }
  21. echo "begin call myFunc()"
  22. myFunc 1 2 3 4 5 6 7 8 9 10 11
  23. echo "return1 $?" # return1 与 return2 顺便验证一下上面所说的
  24. echo "return2 $?"
  25. echo "end call myFunc()"
  26. linux@ubuntu:~/test_shell$ ./hello.sh
  27. begin call myFunc()
  28. =====myFunc()====
  29. 1
  30. 2
  31. 3
  32. 4
  33. 5
  34. 6
  35. 7
  36. 8
  37. 9
  38. 10
  39. 11
  40. 1 2 3 4 5 6 7 8 9 10 11
  41. =====myFunc()====
  42. return1 3
  43. return2 0
  44. end call myFunc()

注意,$10 不能获取第十个参数,获取第十个参数需要${10}。当n>=10时,需要使用${n}来获取参数。

另外,还有几个特殊字符用来处理参数:

参数处理说明$#传递到脚本的参数个数$*以一个单字符串显示所有向脚本传递的参数$$脚本运行的当前进程ID号$!后台运行的最后一个进程的ID号$@与$*相同,但是使用时加引号,并在引号中返回每个参数。$-显示Shell使用的当前选项,与set命令功能相同。$?显示最后命令的退出状态。0表示没有错误,其他任何值表明有错误。




0 0
原创粉丝点击