xargs is widely used in shell scripting; it is usually easy to recast these uses in bash using while read -r; do ... done or while read -ar; do ... done loops.
When should xargs be preferred, and when should while-read loops be preferred?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The thing with
whileloops is that they tend to process one item at a time, often when it’s unnecessary. This is wherexargshas an advantage – it can batch up the arguments to allow one command to process lots of items.For example, a while loop:
and the corresponding
xargs:Here you can see that the lines are processed one-by-one with the
whileand altogether with thexargs. In other words, the former is equivalent toecho 1 ; echo 2 ; echo 3 ; echo 4 ; echo 5while the latter is equivalent toecho 1 2 3 4 5(five processes as opposed to one). This really makes a difference when processing thousands or tens of thousands of lines, since process creation takes time.It’s mostly advantageous when using commands that can accept multiple arguments since it reduces the number of individual processes started, making things much faster.
When I’m processing small files or the commands to run on each item are complicated (where I’m too lazy to write a separate script to give to
xargs), I will use thewhilevariant.Where I’m interested in performance (large files), I will use
xargs, even if I have to write a separate script.