Complete tutorial on xargs in Linux to get the most out of it

Last update: 17/12/2025
Author Isaac
  • xargs converts standard input into arguments for other commands and allows you to chain together tools like find, rm, grep or gzip.
  • Its key options (-0, -I, -n, -P, -p, -t, -a, -d) control how data is read, how commands are formed, and how they are executed.
  • It is essential to exercise extreme caution with destructive commands and rely on confirmations and prior tests to avoid serious errors.
  • Compared to alternatives like find -exec, xargs offers great flexibility and efficiency for handling long lists and launching processes in parallel.

xargs tutorial in linux

If you work with the terminal de Linux Often, sooner or later, you will come across xargs and its peculiar way of chaining commandsIt's one of those utilities that many people overlook, but when you understand it well, it saves you a huge amount of time, especially when handling many files or very long outputs.

Although it's not one of the most famous commands, xargs is a very powerful tool for converting standard input into real arguments from another command. Thanks to that, you can do things like delete hundreds of files, rename them, search for text within a bunch of files, or launch processes in parallel without racking your brain with complicated scripts.

What exactly is xargs in Linux?

The name xargs comes from “extended arguments”, and it describes very well what it does: It takes data from standard input (STDIN) and transforms it into arguments for another commandPut more simply, it takes what comes out of the pipe of a command and uses it as if you had written it by hand after the next command.

Many Linux users hardly ever use xargs, but Its usefulness skyrockets when you work with long lists of itemssuch as file paths, search results, or any text output you want to process. With it, you can automate repetitive tasks and minimize human error by eliminating the need to type endless lists.

In practice, xargs is used to “connect” two commands to each other in a very flexible wayThe first command generates a list of elements (for example, find returns file paths) and xargs is responsible for feeding the second command (for example, rm, grep, mkdir, gzip…) with that data converted into valid arguments.

Almost all common distributions—such as Debian, Ubuntu and most GNU/Linux flavors— xargs comes pre-installed within the coreutils or findutils package, so you usually don't need to install anything extra to use it.

In addition to simplifying the work, xargs can also help you protect your system When you combine it with interactive options or pre-checks, it becomes very interesting if you use it with destructive commands like rm or mv.

How xargs works internally

The basic operation of xargs is simple: It reads from standard input, separates that input into "pieces" (arguments), and builds commands From them. These commands are executed as many times as necessary, depending on the options you have selected and the number of arguments passed in each invocation.

When xargs does not receive any explicit command as a parameter, It uses the echo command by default.This means that if you simply type xargs without anything else, it will display the arguments it has constructed from standard input.

E.g.If you do something as simple as:

echo "uno dos tres" | xargs

What you will get is that xargs lance internally echo one two threeAnd therefore you see that exact line on the screen. It's a quick way to understand how it "translates" the input into arguments.

Another key feature is that xargs takes into account system limitations, such as the maximum command line lengthInstead of building a gigantic order with thousands of arguments at once, it groups them into reasonable blocks, executing the command several times if necessary to avoid exceeding those limits.

All of this is done while respecting rules of argument separation: By default, it considers spaces, tabs, and line breaks as separators.However, as we will see later, you can change this behavior with different options to adapt it to routes with spaces, special line breaks or null separators.

  Easy methods to Change the Title of Your iPhone

Syntax of the xargs command

The general way to use xargs in the terminal is very compact: You place a command that sends data through standard output, add a pipe, and then invoke xargs. with the options and destination command that interest you.

La basic syntax would:

xargs comando

In the typical workflow, you would do something like this:

comando_que_genera_lista | xargs comando_destino

Thus, The destination command is executed with the arguments that come from the command that generates the list.Each group of elements that xargs builds from STDIN is passed as parameters to the command, and it is invoked once or several times depending on the size of the list and the restrictions you have defined.

If you omit the destination command, you already know that xargs will use echo by default and will simply show you the argument reconstructionThis is very practical for testing and debugging before launching more delicate actions.

Most important xargs options

xargs has a good number of options that control how it reads input, how it forms arguments, and how it issues commands. Some of these flags are vital for handling unusual filenames, working interactively, or squeezing performance out of the system. launching processes in parallel.

Among the most commonly used options are the following (there are short and long versions):

  • -0 or –nullWith this option, xargs considers that the arguments are separated by the NULL character (\0) instead of spaces or line breaks. This technique is essential when working with filenames that contain spaces, line breaks, or other problematic charactersIt is often combined with find ... -print0 to ensure that nothing gets broken because of the spaces.
  • -ao –arg-file file: instead of reading the inlet through the standard pipe, xargs takes arguments from a text fileEach line or separator in the file is interpreted as an argument to be processed. This is very useful if you have a pre-filled list of paths or items.
  • -do –delimiter characterThis option allows you specify a custom delimiter character to separate the arguments. This way, each character is interpreted literally and spaces are not used as separators by default. This is useful when the input follows a very specific format.
  • -po –interactive: makes xargs ask before executing each commandIt prints the command it's about to execute and asks for confirmation (usually by responding with y/n). This is especially useful when you plan to use xargs in conjunction with rm, mv, or other potentially destructive actions.
  • -I marker: defines a “token” or marker (like {}) what It is replaced in the command by the current value of the inputThis allows you to build more complex commands or place the argument at the exact point you want within the command.
  • -n numberThis indicates how many arguments are passed to the command each time it is executed. With this, You control the size of each batch and you avoid launching actions with lists that are too large all at once.
  • -P number: sets the maximum number of processes to run in parallel. It's a very convenient way to to parallelize tasks such as compression or heavy processing over many files, speeding up There total task.
  • -t: tells xargs that Print each command to the screen before executing itIt's a very convenient debugging tool because you can see exactly what's going to be launched.

By combining these flags you can adapt xargs to almost any workflow, from simple file cleanup tasks to complex scripts that process data and link it between several programs.

Basic examples to understand xargs

The best way to get the hang of xargs is to see it in action. Below are several practical examples that illustrate it. How to redirect the output of one command to another using xargs as a bridge and taking advantage of its various options.

Create directories from a list

Imagine what you want create multiple folders whose names you have on a single line. With xargs you can do something as straightforward as:

  TikTok Private Messages: How to Enable It? How to activate private messaging on TikTok?

echo "carpeta1 carpeta2 carpeta3" | xargs mkdir

Here, the echo generates the string with the names and xargs splits it into three distinct arguments and passes them to the mkdir commandThe result is that three directories are created in the current directory: folder1, folder2, and folder3, all with a single command.

Execute commands with prior confirmation

When you're about to perform actions that could delete data, it's a good idea to verify before executing them. That's what the option is for. -pA simple example would be:

echo "archivo1 archivo2 archivo3" | xargs -p touch

In this case, xargs will display the touch command with the arguments it intends to use and ask if you want to continue.If you confirm, it will create those files (or update their modification date if they already exist). This approach is perfect as a "safety net" when you're testing riskier combinations.

Search for text within multiple files

A very typical combination is to use `find` to locate files and `xargs` with `grep` to search for text within them. For example, to locate in /etc all files with the .conf extension that contain the word rootYou could use:

find /etc -iname "*.conf" | xargs grep "root"

Here, `find` generates the list of configuration files and xargs handles passing them as arguments to grepwhich will search for the word “root” in each one. It's a very fast way to inspect many configuration files with a single command.

Delete old files from a directory

Another very common use is cleaning up old files. For example, to search in /tmp for all files older than one week and delete themYou could do something like this:

find /tmp -mtime +7 | xargs rm

In this case, find lists each candidate route and xargs invokes rm with those files as argumentsHowever, when it comes to mass deletions, it's advisable to take additional precautions, such as first testing with -print or use xargs -p rm to confirm before deleting.

Advanced examples and best practices with xargs

Beyond the basic examples, xargs shines when you start combining them. Custom bookmarks, parallel execution, and null separatorsThis is where it truly becomes a Swiss Army knife for scripts and automations.

Safely delete files using -0

When you want to delete all files .txt from a directory, the most robust It's combining find with -print0 and xargs with -0 to handle names with spaces correctly:

find . -type f -name "*.txt" -print0 | xargs -0 rm -f

In this command, find generates the list of .txt files and separates each name with a null character through -print0Then, xargs with the option -0 It interprets that null separation and safely passes filenames to rm -f, without getting confused by spaces or strange characters.

Rename files with a prefix using -I

Suppose you want to add the prefix copia_ to all files .jpg from a directory. xargs allows you to construct this type of command using a placeholder that replaces it with the actual name of each file:

ls *.jpg | xargs -I {} mv {} copia_{}

Here, -I {} tells xargs to replace each occurrence of {} within the mv command with the current filenameIn this way, each image is renamed to the same path but starting with copy_. It is a very convenient technique for more elaborate renaming operations.

Compress files in parallel with -P

ls *.log | xargs -n 1 -P 4 gzip

In this order, -n 1 indicates that one file is passed per gzip execution, while -P 4 allows up to four gzip processes to be active at the same timeThis way, you make better use of the CPU cores and significantly reduce the total compression time.

Building more elaborate scripts with sh -c

xargs also integrates very well with shells like sh or bash to run more complex commands for each item in the listFor example, imagine you want to process all the files .txt from a directory, print its name and search within them for a specific pattern, saving all output to a log file.

  How to set boundaries in friendships

One way to do it would be something like this:

find /ruta/a/los/archivos -type f -name "*.txt" | xargs -I {} sh -c 'echo "Procesando {}"; grep "patron" "{}"' >> salida.log

In this construct, find generates the list of files, xargs iterates over each one using -I {} and, for each iteration, executes a small script in sh -cThis script displays the filename and uses grep to search for the pattern within it, redirecting everything to output.log. It's a very illustrative example of the flexibility that xargs provides for chaining related operations.

Use files as an argument source with -a

Once you have a list of routes or items saved in a text file, it may be more convenient to tell xargs that read directly from that file instead of using a pipeThat's what the option is for. -a:

xargs -a lista_de_archivos.txt rm

In this case, xargs will open file_list.txt, interpret its contents as separate entries and will pass those elements to the rm command as arguments, also respecting the other options you can add (such as -n, -po -t).

Security, performance, and alternatives to xargs

Working with xargs involves keeping in mind the security implications and consequences of the commands you are about to executeWhen automating operations on large amounts of files or data, a small oversight in the syntax can end up doing more damage than necessary.

For example, when combining xargs with rm or mv, it is highly recommended to use frequently The -po -t options let you see what will be done before running it en masse.It's also good practice to first try innocuous commands (such as echo or ls) to verify that the argument list is what you expect.

In terms of performance, xargs stands out precisely because efficiently handle long inputs that might exceed the traditional limits of the command lineBy dividing the work into manageable blocks, you avoid errors such as "argument list too long" that appear when you try to pass thousands of arguments at once to a single process.

The option -P It helps to get better performance from the machine by running jobs in parallel, although More processes don't always mean better performance.It depends heavily on whether the task is CPU-bound or I/O-bound, the number of available cores, and the overall system load. It's advisable to run tests to fine-tune the ideal number of concurrent processes.

On the other hand, in some complex scenarios you might prefer to use find with the -exec action instead of xargs. Sometimes, find ... -exec comando {} \; o -exec ... + It can be more readable and self-contained, as it doesn't require an external pipe. In other contexts, xargs offers more flexibility and allows for better component reuse, so The choice depends on the clarity you're looking for and the style of your scripts..

Whichever approach you choose, the key is in Understand how arguments are constructed, how special characters are handled, and what margin of safety you have. before launching mass commands, especially when they affect the file system or critical data.

Mastering xargs takes a while, but once you internalize its logic of "reading from STDIN and converting into arguments", It becomes an indispensable tool in your command-line arsenalFrom small cleaning tasks to advanced processing and search scripts, it will allow you to work faster, more flexibly and more efficiently in any Unix/Linux environment.

unix dos format
Related article:
The Ultimate Dos2Unix and Unix2Dos Guide: Converting Files Between Windows and Unix