How to execute multiple commands after xargs -0? How to execute multiple commands after xargs -0? bash bash

How to execute multiple commands after xargs -0?


find . -name "filename including space" -print0 |   xargs -0 -I '{}' sh -c 'ls -aldF {} >> log.txt; rm -rdf {}'

Ran across this just now, and we can invoke the shell less often:

find . -name "filename including space" -print0 |   xargs -0 sh -c '      for file; do          ls -aldF "$file" >> log.txt          rm -rdf "$file"      done  ' sh

The trailing "sh" becomes $0 in the shell. xargs provides the files (returrned from find) as command line parameters to the shell: we iterate over them with the for loop.


If you're just wanting to avoid doing the find multiple times, you could do a tee right after the find, saving the find output to a file, then executing the lines as:

find . -name "filename including space" -print0 | tee my_teed_file | xargs -0 ls -aldF > log.txtcat my_teed_file | xargs -0 rm -rdf 

Another way to accomplish this same thing (if indeed it's what you're wanting to accomplish), is to store the output of the find in a variable (supposing it's not TB of data):

founddata=`find . -name "filename including space" -print0`echo "$founddata" | xargs -0 ls -aldF > log.txtecho "$founddata" | xargs -0 rm -rdf


I believe all these answers by now have given out the right ways to solute this problem. And I tried the 2 solutions of Jonathan and the way of Glenn, all of which worked great on my Mac OS X. The method of mouviciel did not work on my OS maybe due to some configuration reasons. And I think it's similar to Jonathan's second method (I may be wrong).

As mentioned in the comments to Glenn's method, a little tweak is needed. So here is the command I tried which worked perfectly FYI:

find . -name "filename including space" -print0 | xargs -0 -I '{}' sh -c 'ls -aldF {} | tee -a log.txt ; rm -rdf {}'

Or better as suggested by Glenn:

find . -name "filename including space" -print0 | xargs -0 -I '{}' sh -c 'ls -aldF {} >> log.txt ; rm -rdf {}'