Tuesday, July 17, 2012

find: arguments are not actually one big expression

I first learned about find somewhere around 12 years ago, so the documentation today might contradict me, but I’ve been carrying around in my head this false notion: that flags like -print0 participate in the conditions as a true value while they update a flag that sets the eventual output format.

They don’t, in fact, participate.  find accepts them with -print0 -a «expr» syntax just to mess with you, and outputs the filename as soon as it sees the -print0 option.  That means these two commands are equivalent:
find . -print0 -a «expr»
find . -print0
And in fact, if you offer multiple -print options, you'll get each filename printed out multiple times.

I was intending to do CRLF→LF translations only on text files, and the extension-matching came after the -print0.  Since find emitted no warning, I only noticed the damage when I deployed the website and looked at Firefox valiantly trying to make sense of all the broken images.

The correct way to write the command is actually:
find . «expr» -print0
This triggers the -print0 “option” only once the complete expression has matched.  And suppresses the regular/default -print, of course.

No comments: