7

I just tried :

find . -name "*.[hc]" -print

and

find . -name "*.[hc]"

But both output the same ,is -print useless now?

2 Answers 2

15

Looking at the man page under FreeBSD, I see:

 -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.

So in many cases, -print is unnecessary. However, consider this expression that looks for a file named foo inside of somedir, but not inside any directory named .snapshot:

find somedir -name .snapshot -prune -o -name foo

Given the description referenced above, this will be transformed into:

find somedir ( -name .snapshot -prune -o -name foo ) -print

Which is not the same as what was probably intended:

find somedir -name .snapshot -prune -o -name foo -print

Adding parentheses to make the group a bit more obvious, this is:

find somedir ( -name .snapshot -prune ) -o ( -name foo -print )

To spot the difference, notice that both -prune and -print evaluate to true. So without specifying -print, the first version will print out the current file if either -name .snapshot or -name foo matches.

The second version will only output the current file if -name foo matches.

This is a long winded way of saying that -print is not generally necessary as long as you understand the situations in which it is necessary.

7
  • Incidentally, this was fun. I hadn't realized the subtleties of this before. Thanks, locale!
    – larsks
    Jun 14, 2011 at 2:50
  • @larsks,what does it mean by This primary always evaluates to true?
    – locale
    Jun 14, 2011 at 3:04
  • @locale: Exactly what it says. find is a huge logical expression evaluator, and some of its predicates have side effects as well as returning a boolean value. Jun 14, 2011 at 3:14
  • You give find a bunch of boolean expressions -- like -name foo, which evaluates to True when a file is named foo. Expressions like -print or -prune don't really specify a condition, so they always evaluate to True.
    – larsks
    Jun 14, 2011 at 3:27
  • @larsks,why don't just use -print since they always evalutes to true,isn't it duplicate?
    – locale
    Jun 14, 2011 at 3:30
0

It's also useful when you do other things, but still want to see the matches.

This is a common script call for me:

find . -name '*somepattern*' -print -delete

You must log in to answer this question.