Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I did have a read of the post at How do I execute multiple commands when using find?. Unless I have misunderstood the answer provided, I do not believe it provides the solution I am seeking.

My requirement is to find a specific set of files. If found to then create a directory. If the directory has been successfully created only then to extract the files. Once extracted to delete the source files. How would I be able to achieve this?

share|improve this question
Why don't you use -exec to call a script doing the complicated things? – Nifle Sep 21 '12 at 7:13
@Nifle - Couldn't I just look for a success status code using -exec e.g. if 0 then do something? – PeanutsMonkey Sep 21 '12 at 8:37
up vote 2 down vote accepted

The link you post gives the "correct" answer, in my opinion. Just spawn a shell. Without doing this, you'll not have a large enough toolbox. You could construct a find command in pseudocode such as:

find /path -criteria -exec mkdir {} \; -exec extract {} \; -exec rm {} \;

This will stop on any error, as predicates are naturally and'ed together. But, it gives you insufficient control over the naming of the directory. It's guaranteed to fail.

Spawning a shell resolves this as you'll have the whole shell language at your grasp:

find /path -criteria -exec /bin/sh '
    for d; do
        mkdir "${d##*/}" && tar xvf "$d" && rm "$d"
    done' _ {} +

Note that this version has the side effect of continuing on an error for any given iteration of the loop -- it spawns a single shell for all results. I'd suggest spawning the shell with the -e flag if you want to stop hard on any error.

share|improve this answer
Can I ask what the magic _ and + symbols at the end mean? – stib Sep 25 '12 at 4:08
@stib: The underscore is the argv[0] to the /bin/sh process. It's meaningless (it could be anything you want). The "{} +" is find syntax for "append all the results as arguments to the -exec program" -- argv[1]..argv[n]. It spawns a single process for all results, rather than spawning individual processes for each result, as you would get by using "{} \;". – falconindy Oct 2 '12 at 2:36

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .