MYHOSPITALNOW.COM

Find Trusted Doctors & Hospitals

Discover healthcare providers, compare hospitals, and explore treatment options worldwide.

Free Treatment Quotes • Doctor Search • Hospital Comparison

Find Healthcare Options

www.myhospitalnow.com

xargs in Linux: Practical Commands, Safe Patterns, and Pipeline Workflows

Originally published on 2015-12-12; fully revised and updated.

xargs-commands

The xargs command builds and runs commands from standard input. It is especially useful for DevOps and Linux engineers who need to process long lists of files, IDs, or paths in shell pipelines. In this tutorial, you’ll learn how xargs works, when to use key options, and how to avoid common mistakes with whitespace and destructive commands.

How xargs works in a shell pipeline

At a high level, one command produces items, xargs groups/parses those items, and then executes a target command with the resulting arguments. If you run xargs without specifying a command, it typically uses echo as the default command.

flowchart TD
    A[Producer command emits items] --> B[Choose delimiter strategy]
    B --> C[xargs parses input]
    C --> D[Apply batch and replacement rules]
    D --> E[Build target command arguments]
    E --> F[Execute target command]
    F --> G{More input items}
    G -- yes --> C
    G -- no --> H[Pipeline completes]

Quick option comparison

OptionWhat it doesTypical usePortability note
-n NUse at most N arguments per command runBatching large input listsWidely available
-L NUse at most N input lines per runLine-oriented batchingWidely available
-0Read NUL-delimited inputSafe filename handling with find -print0Common on GNU/BSD, not required by POSIX
-d DELIMUse a custom delimiterNewline-only splitting or custom recordsGNU extension
-I REPLReplace placeholder token in command templateInsert item in the middle of a commandWidely available
-P NRun up to N processes in parallelParallelize independent tasksImplementation-dependent
-t / -pTrace command / prompt before runSafer dry-run and confirmationWidely available

Practical xargs command examples

1) Basic stdin behavior

This reproduces the classic interactive behavior: type input, then press Ctrl+D to end stdin.

xargs
Hi,
Welcome to TGS.
^D
Hi, Welcome to TGS.

2) Limit arguments per command with -n

echo a b c d e f | xargs
# a b c d e f

echo a b c d e f | xargs -n 3
# a b c
# d e fCode language: PHP (php)

3) Split only on newlines with -d ‘\n’ (GNU)

This helps preserve spaces inside each line item.

printf 'alpha\nbeta gamma\n' | xargs -d '\n' -n 1 printf '[%s]\n'
# [alpha]
# [beta gamma]Code language: PHP (php)

4) Safely handle filenames with spaces using -print0 and -0

find . -name "*.c" -print0 | xargs -0 rm -fCode language: JavaScript (javascript)

This pattern is safer than whitespace-delimited parsing when filenames contain spaces, tabs, or newlines.

5) Use placeholder replacement with -I

printf '%s\n' app.log db.log | xargs -I {} cp {} {}.bakCode language: JavaScript (javascript)

6) Legacy find cleanup patterns from the original post

find /usr/preserve -mtime +30 -print | xargs rm -f
find /usr/preserve -size +1024 -print | xargs -n 20 rm -fCode language: PHP (php)

7) Trace or confirm commands before execution

printf '%s\n' file1 file2 | xargs -t rm -f
printf '%s\n' file1 file2 | xargs -p rm -fCode language: JavaScript (javascript)

8) Run independent tasks in parallel

printf '%s\n' 1 2 3 4 | xargs -n 1 -P 2 -I {} sh -c 'echo start {}; sleep 1; echo done {}'Code language: JavaScript (javascript)

xargs vs find -exec: when to choose which

ApproachBest forExampleTrade-off
xargsFlexible pipelines and batching controlfind . -type f -print0 | xargs -0 rm -fNeeds careful delimiter handling
find -exec {} +Simple, safer in one commandfind . -type f -name "*.tmp" -exec rm -f {} +Less explicit control over batching style
find -exec {} \;One-file-at-a-time executionfind . -type f -exec chmod 640 {} \;Can be slower for large file sets

Best practices and common pitfalls

  • Use find -print0 | xargs -0 when dealing with filenames from the filesystem.
  • For destructive commands (rm, mv, chmod), start with xargs -t or replace the command with echo first.
  • Use -n to control command size and avoid oversized invocations.
  • Check your platform’s man xargs for option differences, especially -d and -P.
  • When possible, prefer find -exec {} + for straightforward file operations.

Bottom line: xargs is a powerful command-construction tool for shell automation. Used with safe delimiters and cautious validation, it becomes a reliable building block for DevOps workflows.

Find Trusted Cardiac Hospitals

Compare heart hospitals by city and services — all in one place.

Explore Hospitals
I'm Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms. I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.

Related Posts

Shell Bash Scripting: Assignment & Excercise – 16

This exercise asks for a Bash script that packs a file or directory into a compressed tar archive and then encrypts it with a passphrase. The solution…

Read More

Shell Bash Scripting: Assignment & Excercise – 15

This exercise builds a Bash script that takes an IP address, sends it to the free ip-api.com geolocation API with curl, and uses jq to print the…

Read More

Shell script to git add and commit and push each directory at a time

This page shows how to use a Bash script to stage, commit and push changes one directory at a time. That can mean a folder full of…

Read More

AWS Tutorials: AWS CodeBuild – Buildspec code for creating AMI from running instances

This page has an AWS CodeBuild buildspec that finds every running EC2 instance tagged environment=uat and creates an AMI from each one with the AWS CLI. It…

Read More

Shell Bash Scripting: Assignment & Excercise – 7

This exercise uses Bash, rsync and SSH to copy a local file to a remote backup server, then sends an email when the copy finishes. Below the…

Read More

Shell Bash Scripting: Assignment & Excercise – 4

This exercise asks for a Bash script that checks CPU usage and sends an email when it goes over a threshold. The script above reads /proc/stat, but…

Read More
Subscribe
Notify of
guest
1 Comment
Newest
Oldest Most Voted
Puja kushwaha
Puja kushwaha
1 month ago

The xargs command is a great way to turn command output into useful actions without writing a full script. One important habit is to use -print0 with find and -0 with xargs when filenames may contain spaces or special characters. This helps avoid errors when processing many files. For risky actions like deleting or changing files, test the command with a harmless output first. These small precautions make shell pipelines safer and more reliable.

1
0
Would love your thoughts, please comment.x
()
x