Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can xargs execute a subshell command for each argument?

Tags:

bash

xargs

I have a command which is attempting to generate UUIDs for files:

find -printf "%P\n"|sort|xargs -L 1 echo $(uuid)

But in the result, xargs is only executing the $(uuid) subshell once:

8aa9e7cc-d3b2-11e4-83a6-1ff1acc22a7e file1
8aa9e7cc-d3b2-11e4-83a6-1ff1acc22a7e file2
8aa9e7cc-d3b2-11e4-83a6-1ff1acc22a7e file3

Is there a one-liner (i.e not a function) to get xargs to execute a subshell command on each input?

like image 769
adelphus Avatar asked Mar 26 '15 12:03

adelphus


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.

What does the xargs command do?

The xargs command builds and executes commands provided through the standard input. It takes the input and converts it into a command argument for another command. This feature is particularly useful in file management, where xargs is used in combination with rm , cp , mkdir , and other similar commands.

How do you pass arguments to xargs?

The -c flag to sh only accepts one argument while xargs is splitting the arguments on whitespace - that's why the double quoting works (one level to make it a single word for the shell, one for xargs).

What is difference between xargs and pipe?

pipes connect output of one command to input of another. xargs is used to build commands. so if a command needs argument passed instead of input on stdin you use xargs... the default command is echo (vbe's example). it breaks spaces and newlines and i avoid it for this reason when working with files.


1 Answers

This is because the $(uuid) gets expanded in the current shell. You could explicitly call a shell:

find -printf "%P\n"| sort | xargs -I '{}' bash -c 'echo $(uuid) {}'

Btw, I would use the following command:

find -exec bash -c 'echo "$(uuid) ${1#./}"' -- '{}' \;

without xargs.

like image 108
hek2mgl Avatar answered Oct 02 '22 16:10

hek2mgl