shell脚本函数传参

末蓝、 2022-01-14 04:55 543阅读 0赞

函数可以提高代码复用,在python、java中比较常见。
shell脚本也有函数,可以将一组命令集或语句形成一个可用代码块。

定义格式

  1. 函数名(){
  2. command1
  3. command2
  4. ...
  5. commandN
  6. [ return value ]
  7. }

函数返回值

可以显示增加return语句;如果不加,则将最后一条命令运行结果作为返回值(一般为0,如果执行失败则返回错误代码)。
return后跟数值(0-255)

  1. #! /bin/bash
  2. function test(){
  3. echo "The first param is $1"
  4. return 111
  5. }
  6. test 1
  7. echo "The return of test is $?"

运行结果:

  1. [root@master ~]# sh test_function.sh
  2. The first param is 1
  3. The return of test is 111

Shell函数传参

在Shell中,调用函数时可以向其传递参数。在函数体内部,通过 $n 的形式来获取参数的值,例如,$1表示第一个参数,$2表示第二个参数…即使用位置参数来实现参数传递。

  1. #! /bin/bash
  2. function test(){
  3. echo "The first param is $1"
  4. echo "The second param is $2"
  5. echo "The third param is $3"
  6. echo "The forth param is $4"
  7. echo "The fifth param is $5"
  8. echo "The sixth param is $6"
  9. echo "The seventh param is $7"
  10. echo "The eigth param is $8"
  11. echo "The ninth param is $9"
  12. echo "The tength param is $10"
  13. echo "The 11th param is $11"
  14. return 111
  15. }
  16. test 1 2 3 4 5 6 7 8 9 55 54
  17. echo "The return of test is $?"

运行结果:
[root@master ~]# sh test_function.sh
The first param is 1
The second param is 2
The third param is 3
The forth param is 4
The fifth param is 5
The sixth param is 6
The seventh param is 7
The eigth param is 8
The ninth param is 9
The tength param is 10
The 11th param is 11

注意,$10 不能获取第十个参数,如上结果中$10,打印结果为10。
获取第十个参数需要${10}。

正确姿势,当n>=10时,需要使用${n}来获取参数:

  1. #! /bin/bash
  2. function test(){
  3. echo "The first param is $1"
  4. echo "The second param is $2"
  5. echo "The third param is $3"
  6. echo "The forth param is $4"
  7. echo "The fifth param is $5"
  8. echo "The sixth param is $6"
  9. echo "The seventh param is $7"
  10. echo "The eigth param is $8"
  11. echo "The ninth param is $9"
  12. echo "The tength param is ${10}"
  13. echo "The 11th param is ${11}"
  14. return 111
  15. }
  16. test 1 2 3 4 5 6 7 8 9 55 54
  17. echo "The return of test is $?"

运行结果:
[root@master ~]# sh test_function.sh
The first param is 1
The second param is 2
The third param is 3
The forth param is 4
The fifth param is 5
The sixth param is 6
The seventh param is 7
The eigth param is 8
The ninth param is 9
The tength param is 55
The 11th param is 54
The return of test is 111

发表评论

表情:
评论列表 (有 0 条评论,543人围观)

还没有评论,来说两句吧...

相关阅读

    相关 shell脚本函数

    函数可以提高代码复用,在python、java中比较常见。 shell脚本也有函数,可以将一组命令集或语句形成一个可用代码块。 定义格式 函数名(){