• Shell脚本之:函数


    Shell 也支持函数。Shell函数必须先定义后使用。

    函数的定义与调用

    Shell 函数的定义格式如下:

    function_name () {
        list of commands
        [ return value ]
    }

    函数返回值,可以显式增加return语句;如果不加,会将最后一条命令运行结果作为返回值。

    调用函数只需要给出函数名,不需要加括号。下面给出Shell函数定义和调用的一个简单例子:

    #!/bin/bash
    # Define your function here
    Hello () {
       echo "hello world"
    }
    # Invoke your function
    Hello

    再来看一个带有return语句的函数:

    #!/bin/bash
    funWithReturn(){
        echo "The function is to get the sum of two numbers..."
        echo -n "Input first number: "
        read aNum
        echo -n "Input another number: "
        read anotherNum
        echo "The two numbers are $aNum and $anotherNum !"
        return $(($aNum+$anotherNum))
    }
    funWithReturn
    # Capture value returnd by last command
    ret=$?
    echo "The sum of two numbers is $ret !"

    像删除变量一样,删除函数也可以使用 unset 命令,不过要加上 .f 选项

    函数参数

    在Shell中,调用函数时可以向其传递参数。在函数体内部,通过 $n 的形式来获取参数的值

    #!/bin/bash
    funWithParam(){
        echo "The value of the first parameter is $1 !"
        echo "The value of the second parameter is $2 !"
        echo "The value of the tenth parameter is $10 !"
        echo "The value of the tenth parameter is ${10} !"
        echo "The value of the eleventh parameter is ${11} !"
        echo "The amount of the parameters is $# !"  # 参数个数
        echo "The string of the parameters is $* !"  # 传递给函数的所有参数
    }
    funWithParam 1 2 3 4 5 6 7 8 9 34 73

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

  • 相关阅读:
    AX2009直接交运的bug
    数据库日志
    新蛋中国最新的分类导航,右侧展开菜单,可以修改向左或者向右展开
    用图片代替滚动条的代码
    新蛋网的大图展示效果,缩略图点击显示大图,上一个下一个
    Banner 切换,大小图不同,支持FF和OPERA,IE系列
    下拉菜单,支持所有浏览器
    电容选型
    000.数字电子技术分类
    Altium design16设计技巧
  • 原文地址:https://www.cnblogs.com/runnyu/p/4676738.html
Copyright © 2020-2023  润新知