美文网首页
Shell 函数

Shell 函数

作者: tafanfly | 来源:发表于2019-07-26 16:40 被阅读0次

shell 的函数化一是脚本结构清晰明了, 二是可以重复使用相同代码。
shell 函数必须先定义后才能引用。

函数结构

  • 函数构造 : 可以function name()定义,也可以name()定义
  • 函数参数:在函数体内部,通过 $n 的形式来获取参数的值
  • 函数返回:返回值只能是整数
#!/bin/bash

function name(){
    body
    return
}

函数举例

参数

在函数内部, 通过 $n 的形式来获取参数的值。$0表示脚本的名称, $1表示函数第一个参数, $2表示函数第二个参数,以此类推。
注意:$10 不能获取第十个参数,获取第十个参数需要 ${10}。当 n>=10 时,需要使用 ${n} 来获取参数。

#!/bin/bash

function test_parameters(){
     echo "The zero value is $0"
     echo "The first value is $1"
     echo "The second value is $2"
     echo "The tenth value is $10"
     echo "The tenth value is ${10}"
     echo "The sum of values is $#"
     echo "The total values are $*"
 }

test_parameters 1 2 3 4 5 6 7 8 9 22 33

$ sh test.sh
The zero value is test.sh
The first value is 1
The second value is 2
The tenth value is 10
The tenth value is 22
The sum of values is 11
The total values are 1 2 3 4 5 6 7 8 9 22 33
返回

shell 函数只能return整型。

  • 函数返回值在调用该函数后通过 $? 来获得,注意的是$? 仅对其上一条指令负责
#!/bin/bash

function test_return(){
     return 2
 }

 test_return
 echo $? # 返回 test_return的返回值
 echo $? # 返回上一条命令的值

$ sh test.sh
2
0
  • 如果没有return, 则以最后一条命令运行结果,作为返回值,且值的范围是[0, 255],0表示成功,其他值表示失败。
#!/bin/bash

function test_return(){
     echo 'OK'
 }

 test_return
 echo $? #没有return,则返回最后一条命令运行结果

$ sh test.sh
OK
0
#!/bin/bash

function test_return(){
     ech 'OK'
 }

 test_return
 echo $?

$ sh test.sh
test.sh: line 4: ech: command not found
127
  • 如果 return 其他数据,比如一个字符串,往往会得到错误提示:“numeric argument required”
#!/bin/bash

function test_return(){
     return 'OK'
 }

 test_return
 echo $?

$ sh test.sh
test.sh: line 4: return: OK: numeric argument required
2
  • 可以先定义一个变量,用来接收函数的计算结果,脚本在需要的时候访问这个变量来获得函数返回值
#!/bin/bash

function test_return(){
    echo "OK"
}

result=`test_return`
echo $result
result2=$(test_return)
echo $result2

$ sh test.sh
OK
OK

相关文章

  • shell(六)

    Shell 函数 linux shell 可以用户定义函数,然后在shell脚本中可以随便调用。shell中函数的...

  • shell函数

    shell函数 死循环 shell函数 什么时候用到函数执行的功能类似根据实际需求 ,进行设置shell函数定义格...

  • shell编程二

    目录 一、shell中的函数二、shell中的数组三、shell告警系统 一、shell中的函数 函数就是把一段代...

  • 13. Shell 函数

    函数定义 linux shell 可以用户定义函数,然后在shell脚本中可以随便调用。shell中函数的定义格式...

  • Shell 函数

    linux shell 可以用户定义函数,然后在shell脚本中可以随便调用。 shell中函数的定义格式如下: ...

  • Shell 函数

    linux shell 可以用户定义函数,然后在shell脚本中可以随便调用。 shell中函数的定义格式如下: ...

  • Linux - Bash - Shell 函数

    linux shell 可以用户定义函数,然后在shell脚本中可以随便调用。 Shell 函数 注意:上面的fu...

  • Shell 函数

    linux shell 可以用户定义函数,然后在shell脚本中可以随便调用。 shell中函数的定义格式如下: ...

  • 3.shell 基本特性之~ shell展开详解

    第 3 章目录: 3.1 shell 语法3.2 shell 命令3.3 shell 函数3.4 shell 参数...

  • 4. shell基本特性之~ 重定向

    第 3 章目录: 3.1 shell 语法3.2 shell 命令3.3 shell 函数3.4 shell 参数...

网友评论

      本文标题:Shell 函数

      本文链接:https://www.haomeiwen.com/subject/uxrnkctx.html