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
网友评论