xargs¶
xargs issues commands with the STDIN as arguments, by default appended to the end of the command.
Examples¶
Handle spaces and use the arg as something other than the last token¶
The -I argument takes a string to use as a delimiter for any input. The -print0 arg causes find to terminate each result with a null, which allows it to handle filename with characters that might not play nicely with the shell. We have to then use xargs -0 to make it also handle the null terminated lines. Lots of commands have a feature like this, so be on the lookout for it.
Tun 3 concurrent processes, each consuming 5 results¶
This would run 3 instances of sha256sum with each instance operating on 5 files. Since sha256sum is single-threaded, this would speed things up by using multiple CPU cores instead of being bound to a single CPU core.
use sed to change git files containing a certain string¶
This uses GNU sed -i, on macOS you should use sed -i '' or gsed -i. The -z on git grep causes it to null terminate the entries so xargs -0 will work.
Issue the same command several times in parallel¶
This takes 1 directory as input and starts a sub-shell that cd's to the directory and runs a command. Up to 4 subhells are run in parallel. This is very similar to the GNU parallel command.