[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: GNU find: "print0" and "-type" arguments

Alex Robbins wrote:
> I have a directory that looks like this:
> .
> ├── dir
> └── file
> "dir" is a directory and "file" is a regular file.  I execute:
> find -type d

Here you are using the GNU find extension which allows the path to be
omitted.   In GNU find the path is optional.  In the standard find the
path must be specified.  I always specify the path.  It is portable.

> and get the output:
> .
> ./dir


> This is the expected output.  However, when I execute:
> find -print0 -type d

It would be a lot cleaner to use -print for this example instead of
-print0.  I will use -print for illustrative purposes.  But there
isn't any difference between -print and -print0 for the issue you are
talking about.

> I see (on a terminal screen that does not display null characters):
> ../dir./file

You have the order of arguments backwards.  You wanted to say this:

  find -type d -print

That would do the right thing.  Doing it the other way around doesn't
make any sense.

> The same goes for using "-type f".  It appears as though find
> ignores the -type argument when the -print0 option is passed.  Isn't
> this a bug?

It is a bug in your usage.  Arguments are evaluated from left to right
across the command line.

  -print   -- returns true, prints the full name
  -type X  -- returns true if the type of file matches X

So with this (bad) ordering:

  find . -print -type d  # bad ordering

You get this behavior:

  -print, prints the filename.  All files are printed.
  -type d, returns true if the file is a directory.  But nothing is
  after this on the command line so this value is a noop.

That above bad ordering is exactly the same as:

  find . -print

The other way around works as you intend it.

  find . -type d -print  # good ordering

  -type d, returns true if the file is a directory.  By returning true
  processing continues across the line.  By returning false processing
  stops and the action skips to the next file.
  -print, prints the file name, returns true

Does that help to make sense?


Attachment: signature.asc
Description: Digital signature

Reply to: