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
恩,最后一句就是我们的function的name。
总结
所以我们在shell脚本编写中,要注意:
-
shell的参数要保存在别的变量中,否则function中获取可能出现问题(当赋予参数时); -
function中获取脚本名称,依然使用$0,函数名称就是${FUNCNAME[0]},对于我们输出错误信息有帮助。









网友评论