函数的参数传递

2018年6月11日 星期一

10:14

引子

继续学习,在脚本编写的时候,传递参数出现问题,主要是个数上面,当然,我挖了一些坑来做测试的……

分析

没有引号和双引号

跑一下就知道区别了:


#!/bin/bash

test_fun() {

    echo "$#"

}

echo "no quote"

echo 'the number of parameter in "$@" is '$(test_fun $@)

echo 'the number of parameter in "$*" is '$(test_fun $*)

echo "double quotes"

echo 'the number of parameter in "$@" is '$(test_fun "$@")

echo 'the number of parameter in "$*" is '$(test_fun "$*")

然后运行一下这个命令:


./test.sh test1 "tes t2" 'test3 test4'

the number of parameter in "$@" is 5

the number of parameter in "$*" is 5

the number of parameter in "$@" is 3

the number of parameter in "$*" is 1

疑问

如果我加单引号是什么结果呢?1?

单引号

再修改为:


echo "single quote"

echo 'the number of parameter in "$@" is '$(test_fun '$@')

echo 'the number of parameter in "$*" is '$(test_fun '$*')

运行得出结果:


./test.sh test1 "tes t2" 'test3 test4'

the number of parameter in "$@" is 1

the number of parameter in "$*" is 1

结论

参数传递给函数时,最好使用"$@",因为在测试过程中,只有这种方式是正确的。

在不使用引号或者单引号的情况下,均无法正确获取参数个数。

参考

1. shell 十三問?

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容