Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute multiple commands after xargs -0?

Tags:

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

Is it possible to combine these two commands into one so that only 1 find will be done instead of 2?

I know for xargs -I there may be ways to do it, which may lead to errors when proceeding filenames including spaces. Any guidance is much appreciated.

like image 997
Richard Chen Avatar asked Sep 19 '11 14:09

Richard Chen


People also ask

How do you use xargs with multiple arguments?

Two Types of Commands Using Multiple Arguments Commands can have multiple arguments in two scenarios: All command arguments – COMMAND ARG1 ARG2 ARG3. Option arguments – for example, COMMAND -a ARG1 -b ARG2 -c ARG3.

How do you run multiple commands in one line?

Running Multiple Commands as a Single Job We can start multiple commands as a single job through three steps: Combining the commands – We can use “;“, “&&“, or “||“ to concatenate our commands, depending on the requirement of conditional logic, for example: cmd1; cmd2 && cmd3 || cmd4.

How do I run multiple commands in Bash script?

The Operators &&, ||, and ; The first logical operator we will be looking at will be the AND operator: &&. In Bash, it is used to chain commands together. It can also be used to run two different scripts together.


Video Answer


2 Answers

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.

like image 98
glenn jackman Avatar answered Oct 21 '22 10:10

glenn jackman


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.txt cat 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.txt echo "$founddata" | xargs -0 rm -rdf 
like image 41
Jonathan M Avatar answered Oct 21 '22 08:10

Jonathan M