`

linux,shell学习(六)

阅读更多
shell函数

    1.定义函数        4.函数文件
    2.函数调用        5.载入和删除函数
    3.参数传递        6.函数返回状态

1.定义函数
    语法:
[ function ] funname [()]
{
    action;
    [return int;]
}
说明:
    1、可以带function fun()  定义,也可以直接fun() 定义,不带任何参数。
    2、参数返回,可以显示加:return 返回,如果不加,将以最后一条命令运行结果,作为返回值。 return后跟数值n(0-255
   
#!/bin/bash
    #hello fun
    function hello() {
        echo "hello fun,today is `date`"
        return 1
    }

2.函数调用
   
#!/bin/bash
    #hello fun
    function hello() {
        echo "hello fun,today is `date`"
        return 1
    }
    echo "exec funtion"
    hello
    echo "finish"

3.参数传递
   
#!/bin/bash
    #hello fun
    function hello() {
        echo "hello $1,today is `date`"
        return 1
    }
    echo "exec funtion"
    hello world
    echo "finish"

4.函数文件
   
#!/bin/bash
    #hello fun
    #source function
    . hellofun
    echo "now going to the function hello"
    hello
    echo "back from function hello"

   
function hello() {
        echo "hello,today is `date`"
        return 1
    }

    5.函数的载入查看与删除函数
   
#!/bin/bash
    #hello fun
    #source function
    . hellofun
    set #[color=darkred]查看函数是否载入[/color]
    #unset 删除函数
    echo "now going to the function hello"
    hello
    echo "back from function hello"

   
function hello() {
        echo "hello,today is `date`"
        return 1
    }

    6.函数返回状态
       
#!/bin/bash
    #hello fun
    #source function
    . hellofun
    echo "now going to the function hello"
    hello
    echo $?
    echo "back from function hello"

   
function hello() {
        echo "hello,today is `date`"
        return 1
    }

    注意:一般返回 0 为正确 1 为错误。
    shell函数没有返回值,返回的都是状态值
   

   
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics