Bash Shell – How ‘find -exec’ Passes File Names with Spaces

argumentsbashfindquotingshell

If I have a directory containing some files whose names have spaces, e.g.

$ ls -1 dir1
file 1
file 2
file 3

I can successfully copy all of them to another directory like this:

$ find dir1 -mindepth 1 -exec cp -t dir2 {} +

However, the output of find dir1 -mindepth 1 contains un-escaped spaces:

$ find dir1 mindepth 1
dir1/file 1
dir1/file 3
dir1/file 3

If I use print0 instead of print, the output still contains un-escaped spaces:

$ find dir1 mindepth 1 -print0
dir1/file 1dir1/file 2dir1/file 3

To copy these files manually using cp, I would need to escape the spaces; but it seems that this is unnecessary when cp's aguments come from find, irrespective of whether I use + or \; at the end of the command.

What's the reason for this?

Best Answer

The find command executes the command directly. The command, including the filename argument, will not be processed by the shell or anything else that might modify the filename. It's very safe.

You are correct that there's no need to escape filenames which are represented by {} on the find command line.

find passes the raw filename from disk directly into the internal argument list of the -exec command, in your case, the cp command.

Related Question