本案环境:

[root@bright public]# cat /etc/redhat-release && uname -r 
CentOS release 6.6 (Final)
2.6.32-504.el6.x86_64


使用find 命令时报错:

[root@bright public]# find /opt -type f -name fil* -exce ls -lh {} \;
find: 路径必须在表达式之前: file4.txt
[root@bright public]# find / -name *.txt
find: 路径必须在表达式之前: file78.txt


解决的方法有两种


使用转义符把*转义,即  \*.txt

用引号引起来 ,即 "*.txt"


原因:


首先,shell 会扩展*.txt 如果有匹配,根据匹配的数量会有不同的结果。

0 个匹配: *.txt 仍然保持不变

1 个匹配: *.txt 变成那个匹配的文件名

多于 1 个匹配: *.txt 变成多个单词,也就是所有匹配的文件名

例如:/tmp下有1.txt 2.txt就会报错,因为find命令成为了

find /tmp/ -name 1.txt 2.txt -exec ls -l {} \;

只有1.txt会被识别,2.txt无法识别所以会报错。如果要在 -name 中使用正则表达式,必须加以转义,防止 shell 首先扩展它。转义的办法就是加上\或者引号,这样 -name 选项总是只接受这一个参数。


不过在我机器上不转义也不会报错,我觉得各个linux版本之间可能还是会有差异,这个没有对与错,但是需要有一个标准,写命令的时候要按照标准来写,也就是都加上转义,以免写脚本的时候其他机器报错。


资料来源