美文网首页
shell script中内部参数与外部参数

shell script中内部参数与外部参数

作者: 不正经运维 | 来源:发表于2018-06-11 09:51 被阅读17次

    2018年6月11日 星期一

    09:15

    引子

    shell中也可以直接定义函数,那么函数的的参数与脚本的参数有什么区别呢?话说,我没怎么用过函数的参数。

    分析

    都知道$0-$9是获取shell参数的变量,那么在函数中调用会有什么区别呢?

    测试

    首先,我们编写一个脚本进行测试:

    #!/bin/bash
    
    test_fun() {
        echo '$0 of the function is: '$0
        echo '$1 of the function is: '$1
        echo '$2 of the function is: '$2
    }
    
    echo '$0 of the script is '$0
    echo '$1 of the script is '$1
    echo '$2 of the script is '$2
    
    test_fun para1 "para2 para3"
    

    将上述代码保存为test.sh,并赋予权限。

    chmod 744 test.sh
    ./test.sh test1 "tes t2"
    
    $0 of the script is ./test.sh
    $1 of the script is test1
    $2 of the script is tes t2
    $0 of the function is: ./test.sh
    $1 of the function is: para1
    $2 of the function is: para2 para3
    

    可以看出,$0都是./test.sh,即脚本本身的路径,而$1$2都不同了。

    提问

    是否有办法获取到function的名称呢?请出万能的Google来帮我们找到答案。

    修改test.sh,在test_fun里增加如下代码

    echo ${FUNCNAME[0]}
    

    然后我们再执行一遍:

    ./test.sh test1 "tes t2" 'test3 test4'
    $0 of the script is ./test.sh
    $1 of the script is test1
    $2 of the script is tes t2
    $0 of the function is: ./test.sh
    $1 of the function is: para1
    $2 of the function is: para2 para3
    test_fun
    

    恩,最后一句就是我们的functionname

    总结

    所以我们在shell脚本编写中,要注意:

    1. shell的参数要保存在别的变量中,否则function中获取可能出现问题(当赋予参数时);

    2. function中获取脚本名称,依然使用$0,函数名称就是${FUNCNAME[0]},对于我们输出错误信息有帮助。

    参考

    1. shell 十三問?

    2. How to determine function name from inside a function

    3. 5.2 Bash Variables

    相关文章

      网友评论

          本文标题:shell script中内部参数与外部参数

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