Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I'm trying to run multiple commands on things I have found, how can I achieve this?

find . -exec cmd1; cmd2

does not seem to work; it instead runs cmd2 after cmd1 has been executed on every file.

share|improve this question
add comment

3 Answers

up vote 17 down vote accepted

In this demonstration, I'll use sh -c 'echo first; false' (or true) for the first -exec. That will give some output and also have the selected exit code effect. Then echo second will be used for the second one. Assume that there's one file in the current directory.

$ find . -type f -exec sh -c 'echo first; false' \; -exec echo second \;
first
$ find . -type f -exec sh -c 'echo first; true' \; -exec echo second \;
first
second
$ find . -type f \( -exec sh -c 'echo first; false' \; -false -o -exec echo second \; \)
first
second
$ find . -type f \( -exec sh -c 'echo first; false' \; -false -o -exec echo second \; \)
first
second

A real command of this type would look like:

find . -type f \( -exec command1 \; -false -o -exec command2 \; \)

In the second set, the escaped parentheses group the two -exec clauses. The -false between them forces the test state to "false" and the -o causes the next expression (the second -exec) to be evaluated because of the -false.

From man find:

expr1 expr2
Two expressions in a row are taken to be joined with an implied "and"; expr2 is not evaluated if expr1 is false.

expr1 -a expr2
Same as expr1 expr2.

expr1 -o expr2
Or; expr2 is not evaluated if expr1 is true.

share|improve this answer
    
Ah yes, I forgot about -o. –  Ignacio Vazquez-Abrams Jan 22 '11 at 22:26
add comment

If you don't matter about cmd1 being able to prevent cmd2 from being run due to the error code 0:

find . -exec cmd1 \; -exec cmd2 \;

The only reliable way to get both commands to always run this is to have find invoke a shell that will subsequently run the commands in sequence:

find . -exec bash -c 'cmd1; cmd2' filedumper {} \;
share|improve this answer
add comment

try command:

sudo find -name "*[!0-9][1-9].txt" -exec chmod 744 * {} \; -a -exec ls -l {} \; | sort | parallel ls -l
share|improve this answer
    
Eh, that's not a good idea. The * in the -exec part will expand to all files in the current directory. Especially when running as sudo. –  slhck Nov 24 '13 at 8:43
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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