美文网首页
shell 自定义函数

shell 自定义函数

作者: 一个人一匹马 | 来源:发表于2019-03-12 21:58 被阅读0次
    基本语法
    [ function ] funname[()]
    {
    ​Action;
    [return int;]
    }
    
    funname
    
    经验技巧

    ​(1)必须在调用函数地方之前,先声明函数,shell脚本是逐行运行。不会像其它语言一样先编译。
    ​(2)函数返回值,只能通过$?系统变量获得,可以显示加:return返回,如果不加,将以最后一条命令运行结果,作为返回值。return后跟数值n(0-255)

    案例实操

    ​计算两个输入参数的和

    touch fun.sh
    vim fun.sh
    
    #!/bin/bash
    function sum()
    {
       s=0
       s=$[ $1 + $2 ]
       echo "$s"
    }
    
    read -p "Please input the number1: " n1;
    read -p "Please input the number2: " n2;
    sum $n1 $n2;
    
    ./fun.sh
    Please input the number1: 10
    Please input the number2: 8
    18

    相关文章

      网友评论

          本文标题:shell 自定义函数

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