xargs [options] [command [initial-arguments]]

Linux is an OS that has been developed and oriented to provide users simple commands which can be joined to do more complex task.

Xarg is one of those commands that allows you to compose routines that would be tedious in some other way.

The logic of xarg is the same as a while loop that gets as input the result of a previous command by default using both spaces and newlines as delimiters. For instance, imagine you have to change read permissions of all files in a directory from root to otheruser. You can change them one by one, but it seems not a very enjoyable task, especially if there are a lot of. It would be great if you could filter the files you need and then change their permissions. Here is when xargs comes into action.

I guess you already know how to select files by the owner and then change permission of each one. If so, it is going to be quite easy to create a routine with xarg. First, you have to create a command that filters that files you need. So easy:

find . -user root

This should prompt all the files owned by root in the current directory and subdirectories. Now with the xargs command we can use each of those files as input for our next command:

chown otheruser {here will be placed each result of previous command}

Now we only have to connect this two simple command with xargs and a pipe this way:

find . -user root | xargs sudo chown otheruser

xargs, the backtick and the dollar syntax

Dollar syntax and backtick is absolutelly the same but dollar is prefereable because it leads to less mistakes on readibility. In some cases you can abbreviate above syntax with backtrick instead xargs like

command1 `command2` = command1 $(command2)

Where each single item of command2 output is treated as the argument of command1. This could be more readable and is preferable in some situations, but there are others whose use it is not possible.

The critical difference between backtick and xargs is that backtick syntax pass the output as it had been typed at the shell instead xargs that pass. This means that some commands like rm that allows varags may use backtick but other no.

Either you can’t put arguments to each iteration like you can in varargs.

And thats all!! A very powerful command that takes advantage of pipes and iteration to simplify