-print 现在是查找的无用选项吗?

7 bash find

我刚试过:

find . -name "*.[hc]" -print
Run Code Online (Sandbox Code Playgroud)

find . -name "*.[hc]"
Run Code Online (Sandbox Code Playgroud)

但是两者输出一样,现在-print没用了吗?

lar*_*sks 15

查看 FreeBSD 下的手册页,我看到:

 -print  This primary always evaluates to true.  It prints the pathname of
         the current file to standard output.  If none of -exec, -ls,
         -print0, or -ok is specified, the given expression shall be
         effectively replaced by ( given expression ) -print.
Run Code Online (Sandbox Code Playgroud)

所以在很多情况下,-print是没有必要的。但是,请考虑以下表达式,该表达式查找名为fooin 的文件somedir,但不在任何名为 的目录中.snapshot

find somedir -name .snapshot -prune -o -name foo
Run Code Online (Sandbox Code Playgroud)

鉴于上面引用的描述,这将被转换为:

find somedir ( -name .snapshot -prune -o -name foo ) -print
Run Code Online (Sandbox Code Playgroud)

这与可能的意图不同:

find somedir -name .snapshot -prune -o -name foo -print
Run Code Online (Sandbox Code Playgroud)

添加括号使组更明显一点,这是:

find somedir ( -name .snapshot -prune ) -o ( -name foo -print )
Run Code Online (Sandbox Code Playgroud)

要发现差异,请注意-prune-print评估为true。因此,如果不指定-print,则第一个版本将打印出当前文件(如果 -name .snapshot-name foo匹配)。

如果-name foo匹配,第二个版本将仅输出当前文件。

这是一种冗长的说法,-print只要您了解必要的情况,通常就不需要。