5

I find the manual explanation for find to be a little unclear.

What is the meaning of "but the command line is built by appending each selected file at the end; the total number of invocations of the command will be much less than the number of matched files"  Why is this?

Below is the text of man find

-exec command {} +

This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of ‘{}’ is allowed within the command. The command is executed in the starting directory.

5

What is the meaning of "but the command line is built by appending each selected file at the end; the total number of invocations of the command will be much less than the number of matched files" Why is this?

Let's create some sample files:

touch {1..5}.txt

First, let's run a find command:

$ find . -exec echo my files are: {} +
my files are: . ./1.txt ./5.txt ./4.txt ./3.txt ./2.txt

As you can see {} is replaced with the list of all the files that find found. In this example, we have six matched files yet echo is run only once.

Note that shells have a limit on the number of characters that they will accept on a single command line. find knows this and, if there are too many files to put on one command line, find will run echo several times with different files until all the file names have been processed. This is why "the number of invocations of the command will be much less than the number of matched files."

Let's test this by creating many files in our directory:

touch this_is_a_long_file_name{1..10000}.txt

Now, let's execute a find command:

$ find . -exec bash -c 'echo $# files on this command line' _ {} +
3756 files on this command line
3754 files on this command line
2491 files on this command line

As you can see, even though this directory had over 10,000 files, the exec command was only run three times.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.