美文网首页
2020-02-16 bash对"*"的主动解释会影响函数的结果

2020-02-16 bash对"*"的主动解释会影响函数的结果

作者: 五大RobertWu伍洋 | 来源:发表于2020-02-16 21:07 被阅读0次

bash对"*"的主动解释会影响bash函数的结果

如下定义了一个函数使用find模糊查找文件

function filelocate(){
rawname="$1"
echo find . -maxdepth 4 -name *"${rawname}"* -type f
find . -maxdepth 4 -name *"${rawname}"* -type f
}
alias findm="filelocate"

准备查找项目里的测试文件,结果显示的内容让人诧异

4826 $ findm test
find . -maxdepth 4 -name testAllApis.sh testAllApis_local_v1.sh tests -type f
/usr/bin/find: paths must precede expression: testAllApis_local_v1.sh
Usage: /usr/bin/find [-H] [-L] [-P] [-Olevel] [-D help|tree|search|stat|rates|opt|exec] [path...] [expression]

为何列出了所有当前目录的文件名,构成了一个无效的bash命令?试试单引号:

4829 $ find . -maxdepth 4 -name '*test*' -type f
/usr/bin/find: paths must precede expression: testAllApis_local_v1.sh
Usage: /usr/bin/find [-H] [-L] [-P] [-Olevel] [-D help|tree|search|stat|rates|opt|exec] [path...] [expression]

还是一样的错误,看来要上转义字符试试了:

4830 $ find . -maxdepth 4 -name '\*test\*' -type f
./testAllApis.sh
./testAllApis_local_v1.sh
./tests/function.test.js

所以最规范的函数定义是:

function filelocate(){
rawname="$1"
echo find . -maxdepth 4 -name "\*""${rawname}""\*" -type f
find . -maxdepth 4 -name "\*""${rawname}""\*" -type f
}

测试结果:

4839 $ findm test
find . -maxdepth 4 -name \*test\* -type f
./testAllApis.sh
./testAllApis_local_v1.sh
./tests/function.test.js

相关文章

网友评论

      本文标题:2020-02-16 bash对"*"的主动解释会影响函数的结果

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