19

I want to run:

./my_script.py a_file &

... on all files in the current folder that end with .my_format, so I do:

find . -type f -name "*.my_format" -exec ./my_script {} & \;

but it doesn't work. How should I include & in the -exec parameter?

4
  • 2
    possible duplicate of Can the find command's "exec" feature start a program in the background? Commented Sep 29, 2014 at 17:24
  • is there a point in pointing it out one year later? Commented Sep 30, 2014 at 9:21
  • 1
    I got to this question when facing this very problem, and it's definitively not a bad question. At this point, mentioning it's a duplicate is a way of notifying future readers other answers are available, that's all. Commented Sep 30, 2014 at 14:06
  • Finally, only this answer to similar question helped me. Commented Aug 10, 2017 at 16:15

2 Answers 2

19

Try this:

$ find . -type f -name "*.my_format" -exec sh -c './my_script {} &' \;

The mostly likely reason your attempt didn't work is because find executes the command using one of the exec(3) family of standard c library calls which don't understand job control - the & symbol. The shell does understand the "run this command in the background" hence the -exec sh ... invocation

Sign up to request clarification or add additional context in comments.

5 Comments

Oh ok, thanks. So sh is the basic shell on all linux machines, right?
Recent linux distros symlinks /bin/sh to a shell that is posix-sh compliant.
If we spawn a new shell for each execution why would we also need to add the executed command in the background?
The shell is executed one after another. Putting it in the background have a side effect of the shell script to be run in parallel (as many as the CPU can handle at one time).
This works, but handle with care. If there are a lot of files in the tree you're recursing, you're system will probably lock up.
5

Try this find command:

find . -type f -name "*.my_format" -exec bash -c './my_script "$1" &' - '{}' \;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.