I’m pretty much confused on this. Need some clarifications.
Example 1 :
pgrep string | xargs ps
Example 2 :
find . | xargs grep whatever
From Example 1, I gather it’s this way:
Search for a “string” which is part of name of running process and return the process-ids of all the matches to ‘xargs ps’ -> which just appends ps to the matches (which are process-ids themselves) to get the same output as :
ps <processid>
Can someone explain what xargs really does in this case?
From Example 2, I gather it’s this way:
It’s to search for some “string” recursively from the current working directory.
Here, how exactly does ‘xargs’ work?
I was of the opinion that ‘xargs’ repeatedly appends data from standard input to the ‘argument’ given to xargs (which usually is a UNIX command by itself).
From xargs() man page :
xargs reads items from the standard input, delimited by blanks (which can be
protected with double or single quotes or a backslash) or newlines, and
executes the command (default is /bin/echo) one or more times with any
initial-arguments followed by items read from standard input. Blank lines
on the standard input are ignored.
In general xargs is used like this
where
progis expected to output one or more newline/space separated results. The trick is thatxargsdoes not necessarily callutilityonce for each result, instead it splits the results into sublists and callsutilityfor every sublist. If you want to force xargs to callutilityfor every single result you will need to invoke it withxargs -L1.Note that
xargspromises you that the sublist sent toutilityis shorter thanARG_MAX(If you’re curious, you can get the current value ofARG_MAXusinggetconf ARG_MAX.) This is how it avoids those dreaded “Argument list to long” errors.