为什么 **find** 命令找不到任何内容?

17

我正在寻找安装在我的系统上的shell脚本文件,但是find命令不起作用:

$ find /usr -name *.sh

但我知道有很多脚本可用,例如:

$ ls /usr/local/lib/*.sh
/usr/local/lib/tclConfig.sh  
/usr/local/lib/tkConfig.sh
为什么find不起作用?

2
这是一个超级用户的问题吗? - endolith
这更适合在UnixSE上。 - Richard de Wit
3个回答

54

试着引用通配符:

$ find /usr -name \*.sh

或者:
$ find /usr -name '*.sh'

如果当前工作目录中有与*.sh匹配的文件,通配符会在find命令看到它之前进行展开。如果你的工作目录中有一个名为tkConfig.sh的文件,则find命令会展开为:

$ find /usr -name tkConfig.sh

这将只会找到名为tkConfig.sh的文件。如果您有多个与*.sh匹配的文件,find命令将产生语法错误:

$ cd /usr/local/lib
$ find /usr -name *.sh
find: bad option tkConfig.sh
find: path-list predicate-list

再次解释原因是通配符会扩展到这两个文件:

$ find /usr -name tclConfig.sh tkConfig.sh

使用通配符的引用可以防止其过早扩展。

另一种可能性是 /usr 目录或其子目录之一是符号链接。find 命令通常不会遵循链接,因此您可能需要使用 -follow 选项:

$ find /usr -follow -name '*.sh'

如果文件是shell脚本但缺少.sh扩展名怎么办?也许可以使用类似于 find /xyz | xargs file | grep shell的命令? - Paul Ratazzi
然而,有多少Shell脚本没有.sh扩展名呢? - user4822346
有没有一种通用的方法来确定通配符何时/在哪里被扩展? - isaacg
在 Windows 中长大,因为“所有”都有扩展名,所以我看过很多 *ix 上省略了 .sh 的脚本。 - Jan

15

在某些系统上(例如 Solaris),没有默认操作,因此您需要添加 -print 命令。

find /usr -name '*.foo' -print

1
过去我曾遇到过这个问题。但是我要指出的是,在现代的Solaris系统上,默认情况下会自动开启-print选项。事实上,我已经找不到不再以这种方式工作的find命令了。 - Jon Ericson

8

在寻找硬盘上的文件时,建议使用“locate”命令,它可以即时查找(检索每日构建的索引)。 例如:

locate '/usr*.sh'

一个好的建议。(我不知道为什么我的crontab里没有它,所以我必须在我的机器上运行updatedb来测试这个想法。如果没有最新的数据库,那么不使用locate的主要原因就是这个。) - Jon Ericson
还有一些系统默认没有安装locate - 我发现我需要在我的树莓派上安装mlocate软件包 - 别忘了之后运行sudo updatedb命令来构建索引... - SlySven

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接