Skip to content

Linux commands: xargs

New Course Coming Soon:

Get Really Good at Git

A quick guide to the `xargs` command, used to pass output of a command and use it as argument to another command

The xargs command is used in a UNIX shell to convert input from standard input into arguments to a command.

In other words, through the use of xargs the output of a command is used as the input of another command.

Here’s the syntax you will use:

command1 | xargs command2

We use a pipe (|) to pass the output to xargs. That will take care of running the command2 command, using the output of command1 as its argument(s).

Let’s do a simple example. You want to remove some specific files from a directory. Those files are listed inside a text file.

We have 3 files: file1, file2, file3.

In todelete.txt we have a list of files we want to delete, in this example file1 and file3:

We will channel the output of cat todelete.txt to the rm command, through xargs.

In this way:

cat todelete.txt | xargs rm

That’s the result, the files we listed are now deleted:

The way it works is that xargs will run rm 2 times, one for each line returned by cat.

This is the simplest usage of xargs. There are several options we can use.

One of the most useful in my opinion, especially when starting to learn xargs, is -p. Using this option will make xargs print a confirmation prompt with the action it’s going to take:

The -n option lets you tell xargs to perform one iteration at a time, so you can individually confirm them with -p. Here we tell xargs to perform one iteration at a time with -n1:

The -I option is another widely used one. It allows you to get the output into a placeholder, and then you can do various things.

One of them is to run multiple commands:

command1 | xargs -I % /bin/bash -c 'command2 %; command3 %'

You can swap the % symbol I used above with anything else, it’s a variable

The xargs command works on Linux, macOS, WSL, and anywhere you have a UNIX environment

Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching May 21, 2024. Join the waiting list!

Here is how can I help you: