3 ms·
One day I have to learn how to use xargs
by unixhero 9y ago
One day I have to learn how to use xargs
- limaoscarjuliet 9y agoYou and me, both of us. I once combined rpm -e with xargs rpm -ql to the tune of getting all packages uninstalled from the system in one swift command. It was a test system so all good. But I'm still not sure what I was thinking.
- pwg 9y agoThe simplest use case for xargs is that you have a list of filenames and you want to feed that list to a command that only accepts filenames as CLI parameters: I.e., 'find' generates a list of filenames. But 'stat' (for example) only accepts file names as parameters on the command line. You combine these two using 'xargs': find -type f -print0 | xargs -0 stat --format="%y\t%n" And you get an output of human readable modification times, a tab, the filename and a newline. Note, the "-print0" to find instructs find to output null terminated filenames, and the -0 to xargs instructs xargs to expect to receive null terminated filenames. These switches (they may be specific to GNU coreutils) allow for handling filenames with any possible character in them correctly (i.e., spaces cause no troubles). For this use case, remembering how/when to use xargs is easy. The more esoteric usages are the ones where "man xargs" is often handy.
- cat199 9y agoIt's pretty much 'apply' for shell arguments https://en.wikipedia.org/wiki/Apply https://en.wikipedia.org/wiki/Apply use it many places instead of a for loop: for x in ; do <cmd> $x done is: echo |xargs cmd Assuming 'cmd' can take multiple arguments. If not, use 'xargs -L 1 cmd' to run cmd 1x per arg. GNU xargs has -1, but -L 1 is portable to xargs in the BSDs and others.. plus it's good to know -L in case you ever need to -L 2, etc. using echo as a driver is not the best example, but anyhow.
- cat199 9y agoalso of note is: -t : print the commands being run -I %: interpolate file name in command string. e.g. ls .mp4 |xargs -t -L 1 -I % scp % me@somebox:/movies to scp individual files (replaced in %) to a destination, one at a time, printing each command as it is run. Again, not the best example since you can scp .mp4 me@sombeox:/movies or rsync, etc. but you get the idea.
- bitexploder 9y agoFind has exec as well. I tend to use this when searching for things.