If you try to pipe the output from one Linux command into another, you may run into errors where the command fails because its argument list is too long.

Fortunately, there's a command on Linux systems that properly formats arguments to commands. It's called xargs and here's how to use it.

Why Use xargs?

What xargs does is that it receives standard output and formats it so that another command can receive it. While many Linux utilities can accept standard input, some only accept arguments as input.

These may fail if you try to redirect standard input to the command. Some commands still only accept a certain number of arguments and xargs takes care of this for you.

How to Use xargs on Linux

You can call xargs like this:

        xargs [command]
    

xargs keeps track of the length of arguments a command accepts and formats standard input to output an argument list to supply to the command. When it reaches the limit of a command line, it will invoke the command again with the remaining arguments.

Using xargs in Pipelines

xargs' usefulness comes when it's used in pipelines. A contrived example would be piping cat to echo, which is a command that only accepts arguments, not standard input.

        cat | echo
    

This will cause echo to print whatever you type on one line as soon as you hit Ctrl + D.

xargs is most commonly used with the find command, with the find command being used to list files and xargs used to process the list of files in some way.

The find command syntax is hairy enough, so why bring another command into it? If you use find's "-exec" option, it will spin up a new process each time it searches through a file in the directory. Using xargs is more efficient.

You might want to delete files in a directory that are older than a certain date, such as 90 days. To do this, you'd use this pipeline:

        find . -mtime +90 -print | xargs rm
    

xargs Helps Linux Commands Process Input Correctly

With xargs, you can now make sure that commands will take arguments the way you expect them to. Combined with find, it will let you process files on your machine quickly.

The ability to redirect input and output in the shell is one of the enduring strengths of Linux as an outgrowth of the Unix philosophy. If you want to learn more about how Linux input/output redirection works, read on.