fbpx Linux xargs Command: Complete Guide with Practical Examples | Certificação Linux

Linux xargs Command: Batch Argument Processing with Practical Examples

📅 01/01/2019 ⏱ 6 min ✍️ Uira Ribeiro
Linuxcommands
Linux xargs Command: Batch Argument Processing with Practical Examples
Exam Pass App — mais de 7.000 questões LPI, offline, em 5 idiomas, disponível no Android e na App Store
Available on
Google Play
Available on
App Store

The xargs command is one of the most powerful tools in the Linux terminal. It solves a simple but frequent problem: many commands (rm, chmod, cp, ssh) don't read from standard input — they need to receive arguments directly on the command line. xargs makes this bridge, transforming the output of a pipe into arguments.

Without xargs, a find . -name "*.log" | rm simply doesn't work. With xargs, it becomes find . -name "*.log" | xargs rm and processes hundreds of files at once.

xargs syntax

comando | xargs [opções] [comando_destino]

xargs reads items from standard input (separated by space, tab or newline by default) and passes them as arguments to the destination_command.

Basic example

# Sem xargs — não funciona como esperado
echo "arquivo.txt" | cat

# Com xargs — passa "arquivo.txt" como argumento para cat
echo "arquivo.txt" | xargs cat

# Vários arquivos de uma vez
ls *.conf | xargs wc -l

Main xargs options

OptionWhat it doesExample
-n NMaximum of N arguments per callxargs -n 2
-I {}Replaces {} with the argument in the commandxargs -I{} mv {} {}.bak
-P NRuns N processes in parallelxargs -P 4
-0Uses null as separator (for names with spaces)find -print0 | xargs -0
-tShows the command before executing (verbose)xargs -t rm
-pPrompts for confirmation before each executionxargs -p rm
-L NN lines of input per callxargs -L 1
--no-run-if-emptyDoes not run if input is emptyxargs --no-run-if-empty rm

Practical use cases

1. Delete files found by find

This is the most common combination. find lists the files and xargs passes all of them to rm at once, much more efficient than find -exec rm {} \;:

# Deletar todos os arquivos .log com mais de 30 dias
find /var/log -name "*.log" -mtime +30 | xargs rm -f

# Ver quais seriam deletados antes de executar
find /var/log -name "*.log" -mtime +30 | xargs -t rm -f

2. Filenames with spaces — use -0

The biggest problem with standard xargs is that spaces break arguments. The solution is to use find -print0 together with xargs -0:

# ERRADO — quebra em nomes com espaço
find . -name "*.jpg" | xargs rm

# CORRETO — separador null preserva nomes com espaço
find . -name "*.jpg" -print0 | xargs -0 rm

3. Replacement with -I {} to rename and transform

With -I {} you define where the argument will appear in the command — not necessarily at the end:

# Criar backup de cada arquivo .conf
ls *.conf | xargs -I{} cp {} {}.bak

# Mover arquivos para outro diretório mantendo o nome
find . -name "*.py" | xargs -I{} mv {} /opt/scripts/{}

# Criar diretórios com base em uma lista
cat projetos.txt | xargs -I{} mkdir -p /var/www/{}

# Fazer curl para múltiplos endpoints
cat urls.txt | xargs -I{} curl -s {} -o /dev/null -w "%{http_code} {}\n"

4. Parallel execution with -P

The -P N flag runs N simultaneous processes — ideal for operations that can be parallelized like downloads, compression or image processing:

# Comprimir 8 arquivos em paralelo (usa múltiplos núcleos)
find . -name "*.log" -print0 | xargs -0 -P 8 gzip

# Baixar múltiplos arquivos em paralelo
cat lista_de_urls.txt | xargs -P 5 -I{} wget -q {}

# Redimensionar imagens em paralelo com ImageMagick
find . -name "*.png" -print0 | xargs -0 -P 4 -I{} convert {} -resize 800x600 {}

5. Control number of arguments with -n

By default, xargs passes all arguments at once. With -n N you limit how many go in each call — useful when the command has a limit or when you want to process in groups:

# Mostrar 2 arquivos por vez com cat
ls *.txt | xargs -n 2 cat

# Verificar 10 URLs por vez
cat urls.txt | xargs -n 10 curl --head

# Ver como os argumentos são agrupados (verbose)
seq 1 10 | xargs -n 3 echo
# Saída:
# 1 2 3
# 4 5 6
# 7 8 9
# 10

6. Search text in many files with grep

# Buscar "erro crítico" em todos os logs do mês passado
find /var/log -name "*.log" -mtime -30 -print0 | xargs -0 grep -l "erro crítico"

# Contar ocorrências por arquivo
find . -name "*.php" -print0 | xargs -0 grep -c "sql_query"

# Buscar e substituir em múltiplos arquivos (com sed)
grep -rl "texto_antigo" . | xargs sed -i 's/texto_antigo/texto_novo/g'

7. Operations on remote servers

# Verificar status de serviço em múltiplos servidores
cat servidores.txt | xargs -I{} ssh {} "systemctl status nginx | grep Active"

# Copiar chave pública para vários servidores
cat servidores.txt | xargs -I{} ssh-copy-id user@{}

# Reiniciar serviço em todos os nós do cluster
cat nodes.txt | xargs -I{} -P 5 ssh {} "sudo systemctl restart app"

8. Check if input is empty

Without --no-run-if-empty, xargs runs the command even without arguments, which can cause problems:

# PERIGOSO — rm sem argumentos pode falhar ou apagar coisas erradas
find . -name "*.tmp" | xargs rm

# SEGURO — não executa rm se não houver arquivos .tmp
find . -name "*.tmp" | xargs --no-run-if-empty rm

xargs vs find -exec

Both solve similar problems, but with different behaviors:

xargsfind -exec {} \;find -exec {} +
SpeedFast (few processes)Slow (1 process per file)Fast (groups arguments)
Names with spaceNeeds -print0 / -0Works nativelyWorks natively
Parallel controlYes (-P)NoNo
Complex pipelinesYesNoNo
# find -exec equivalente ao xargs (mais lento, 1 processo por arquivo)
find . -name "*.log" -exec rm {} \;

# find -exec + agrupa argumentos (similar ao xargs padrão)
find . -name "*.log" -exec rm {} +

# xargs com -print0/-0 é a opção mais segura e flexível
find . -name "*.log" -print0 | xargs -0 rm

Quick reference

# Deletar em lote com segurança
find . -name "*.tmp" -print0 | xargs -0 --no-run-if-empty rm

# Renomear adicionando extensão
ls *.txt | xargs -I{} mv {} {}.bak

# Comprimir em paralelo
find . -name "*.log" -print0 | xargs -0 -P $(nproc) gzip

# Buscar e substituir em múltiplos arquivos
grep -rl "padrão" . | xargs sed -i 's/padrão/novo/g'

# Executar em múltiplos servidores
cat hosts.txt | xargs -I{} -P 10 ssh {} "uptime"

# Ver como os argumentos serão divididos (dry run)
echo "a b c d e" | xargs -n 2 echo

Tips and pitfalls

  • Always use -print0 | xargs -0 when filenames may have spaces — which is almost always on general-purpose systems.
  • Use -t to debug before running destructive operations like rm.
  • Combine -P $(nproc) to take advantage of all available cores in parallelizable operations.
  • -I{} implies -L 1 — each line becomes a separate call to the command.
  • Be careful with quotes in replacement: xargs -I{} sh -c 'echo "valor: {}"' may have unexpected behavior with spaces in arguments.
Uira Ribeiro

Prof. Uirá Ribeiro

Chair do Board do Linux Professional Institute

After years of watching professionals waste hours on simple tasks because they didn't know the right Linux tools, I decided to teach.
Today I'm the author of most of LPI's official Learning Materials and mentor to over 14,000 certified students.

See my full story →

That was just one piece. The course teaches the whole path — from your first command to exam day.

Certificação Linux — a plataforma líder em certificações Linux no Brasil
WhatsApp