Skip to content

xargs

105 commands

Builds and runs command lines from standard input — the glue for batch operations and parallel jobs in pipelines.

  • pipelines
  • batch
  • parallel

Install xargs

sudo apt install findutils

Basic Syntax3

echo 'file1 file2' | xargs

Demonstrates default behavior which echoes input arguments to stdout.

seq 5 | xargs echo

Takes a list of numbers from stdin and prints them as a single line of arguments.

cat files.txt | xargs cat

Reads filenames from a text file and passes them to cat to display content.

Argument Limiting2

seq 10 | xargs -n 1 echo

Limits execution to one argument per command line invocation.

seq 10 | xargs -n 2 echo

Groups input into pairs of two arguments per command execution.

Delimiter Control2

echo '1,2,3,4' | xargs -d , echo

Uses a comma as a custom delimiter instead of default whitespace.

echo 'user1:user2:user3' | xargs -d : -n 1 echo

Splits input by colon delimiter and processes each item individually.

Input Management1

xargs -a inputs.txt echo

Reads arguments directly from a file instead of standard input.

Execution Safety3

find . -name '*.tmp' | xargs -p rm

Prompts the user for confirmation before executing each command.

find . -name '*.log' | xargs -t rm

Prints the full command line to stderr before executing it (verbose mode).

Link
find . -name '*.nonexistent' | xargs -r rm

Prevents the command from running if standard input is empty.

Link

Argument Replacement2

find . -name '*.txt' | xargs -I {} mv {} {}.bak

Uses {} as a placeholder to insert the argument into specific positions in the command.

Link
seq 5 | xargs -I % echo 'Processing ID: %'

Uses a custom placeholder symbol (%) to format output strings.

Link

Line Based Processing1

ls -1 | xargs -L 1 echo 'File:'

Forces xargs to treat each line of input as a distinct argument unit.

Link

Null Termination2

find . -name '*.png' -print0 | xargs -0 rm

Handles filenames with spaces or newlines correctly using null character delimiters.

Link
grep -rZ 'error' . | xargs -0 rm

Processes null-terminated output from grep for safe file handling.

Link

Command Size Limits2

seq 1000 | xargs -s 2048 echo

Limits the maximum size of the command line to 2048 characters.

Link
find . -type f | xargs --show-limits

Displays the operating system limits on command-line length and buffers.

Link

Process Control1

seq 100 | xargs -E 50 echo

Stops processing input immediately when the string '50' is encountered.

Link

Parallel Execution4

seq 10 | xargs -n 1 -P 2 sleep 1

Runs commands in parallel using up to 2 concurrent processes.

Link
find . -name '*.jpg' -print0 | xargs -0 -n 1 -P 4 convert -resize 50%

Batch processes image resizing using 4 parallel threads for performance.

Link
cat urls.txt | xargs -n 1 -P 10 curl -O

Downloads files from a list of URLs using 10 concurrent connections.

Link
seq 100 | xargs -P 0 -n 1 echo

Spawns as many processes as possible (unlimited) to handle the input.

Link

File Operations3

find /var/log -name '*.log' | xargs tar -cvf logs.tar

Archives a list of found log files into a single tarball.

Link
cat files.txt | xargs -I {} cp {} /backup/{}

Copies files listed in a text file to a backup directory individually.

Link
ls *.conf | xargs -I {} cp {} {}.backup

Creates a backup copy of every configuration file in the current directory.

Link

Directory Operations1

cat folders.txt | xargs mkdir -p

Creates a directory structure based on a list of names.

Link

System Administration3

find /home -name 'id_rsa' | xargs chmod 600

Fixes permissions on SSH private keys found in home directories.

Link
cat users.txt | xargs -n 1 useradd

Bulk creates users from a text file list.

Link
cat groups.txt | xargs -I {} groupadd {}

Bulk adds system groups from a file using replacement logic.

Link

Data Processing2

find . -type f -name '*.csv' | xargs cat | wc -l

Counts the total lines across all CSV files in a directory tree.

Link
ls | xargs -n 1 -I {} sh -c 'echo -n {}; echo -n " "; wc -c < {}'

Uses a subshell to print the filename and its byte count on the same line.

Link

Complex Commands1

find . -name '*.sh' | xargs -I {} sh -c 'chmod +x {}; echo Executable: {}'

Executes multiple commands per argument by invoking a shell explicitly.

Link

Integration3

docker ps -q | xargs -r docker stop

Stops all running Docker containers, doing nothing if none are running.

Link
docker images -q | xargs -r docker rmi

Removes all Docker images found on the system.

Link
git ls-files | xargs wc -l

Counts lines of code for all files tracked by git.

Link

Network Automation2

cat hosts.txt | xargs -n 1 -I {} ping -c 1 {}

Pings a list of hosts once each to check reachability.

Link
cat domains.txt | xargs -n 1 host

Performs DNS lookups for a batch list of domains.

Link

SOC Automation3

find /var/www/html -type f | xargs sha256sum > baseline_hashes.txt

Generates SHA256 hashes for all web files to create an integrity baseline.

Link
grep -l 'malware_signature' /var/log/* | xargs -I {} cp {} /quarantine/

Identifies log files containing a signature and copies them to a quarantine folder.

Link
cat suspicious_ips.txt | xargs -I {} grep {} /var/log/auth.log

Searches authentication logs for activity related to a list of suspect IPs.

Link

Blue Team Validation2

find /etc -type f -perm -o+w | xargs ls -ld

Lists details of any files in /etc that are world-writable for audit purposes.

Link
cat users.txt | xargs -I {} chage -l {}

Checks password expiry information for a specific list of users.

Link

Incident Response2

pgrep -u malicious_user | xargs -r kill -9

Force kills all processes owned by a specific malicious user account.

Link
lsof -t -i :8080 | xargs -r kill

Terminates any process currently listening on port 8080.

Link

Advanced Workflow3

find . -name '*.txt' -print0 | xargs -0 -I {} sh -c 'cat {} >> combined.log; echo "---EOF---" >> combined.log'

Concatenates files safely while injecting a custom separator between content.

Link
find . -name '*.gz' | xargs -n 1 -P 4 gunzip

Decompresses all gzip files in the directory using 4 parallel workers.

Link
cat list.txt | xargs -d '\n' -n 1 echo

Explicitly sets newline as delimiter to handle items containing spaces correctly without null termination.

Link

Cleanup2

find . -type d -empty -print0 | xargs -0 rmdir

Recursively removes empty directories safely using null delimiters.

Link
find /tmp -mtime +7 -print0 | xargs -0 rm -f

Deletes files in tmp that are older than 7 days using safe handling.

Link

AWS/Cloud (Simulated)1

cat buckets.txt | xargs -I {} echo 'aws s3 ls s3://{}'

Constructs AWS CLI commands to list contents of multiple S3 buckets.

Link

Kubernetes (Simulated)1

kubectl get pods -o name | xargs -n 1 kubectl delete

Deletes all pods in the current namespace by passing names to delete command.

Link

Advanced Limits1

seq 1000 | xargs -n 50 -x echo

Forces exit if the constructed command line exceeds the system size limit.

Link

Nested Xargs1

ls | xargs -n 1 -I {} sh -c 'echo {} | xargs echo nested:'

Demonstrates invoking xargs inside a command executed by xargs.

Link

Debugging1

find . -name '*.txt' | xargs -t -n 1 touch

updates timestamps on files while printing the exact command being run for verification.

Link

Process Info1

seq 10 | xargs -P 2 -n 1 --process-slot-var=SLOT sh -c 'echo Running on slot $SLOT'

Exposes the parallel process slot ID as an environment variable to the child process.

Link

Input Preprocessing1

cat raw_data.txt | tr ' ' '\n' | xargs -n 1 echo

Preprocesses space-separated data into newlines before passing to xargs.

Link

Batch Renaming1

ls *.jpg | xargs -n 1 -I {} bash -c 'mv "$1" "${1%.jpg}.png"' _ {}

Uses bash parameter expansion inside xargs to rename file extensions.

Link

Permissions Auditing1

find / -perm -4000 -print0 2>/dev/null | xargs -0 ls -ld

Locates and details all SUID executables on the system safely.

Link

Artifact Collection1

cat artifact_list.txt | xargs -I {} tar -rvf collection.tar {}

Appends specific files listed in a text file to an existing tar archive.

Link

Remote Execution1

cat servers.txt | xargs -n 1 -I {} ssh {} 'uptime'

Runs the uptime command sequentially on a list of remote servers.

Link

Remote Execution Parallel1

cat servers.txt | xargs -P 5 -n 1 -I {} ssh {} 'uname -a'

Runs commands on multiple remote servers in parallel to save time.

Link

Database Maintenance1

cat tables.txt | xargs -I {} echo 'OPTIMIZE TABLE {};' | mysql -u root my_db

Constructs SQL queries for a list of tables and pipes them to the MySQL client.

Link

Dependency Management1

cat packages.txt | xargs apt-get install -y

Installs a list of software packages from a file in a single transaction.

Link

Code Quality1

find src/ -name '*.js' | xargs eslint

Runs a linter against all JavaScript files found in the source directory.

Link

String Manipulation1

echo '  padded  ' | xargs

Trims leading and trailing whitespace from the input string.

Link

Interactive Filtering1

ls | xargs -p -n 1 echo deleting

Simulates a delete operation where the user must approve every single file.

Link

Disk Usage1

find . -maxdepth 1 -type d | xargs -I {} du -sh {}

Calculates the disk usage summary for every subdirectory in the current path.

Link

Archive Extraction1

ls *.tar.gz | xargs -n 1 tar -xzvf

Extracts multiple tar.gz archives sequentially.

Link

Process Signals1

pgrep java | xargs -r kill -SIGTERM

Sends a graceful termination signal to all Java processes.

Link

Batch Comparison1

ls *.bak | xargs -I {} sh -c 'diff {} ${0%.bak}' {}

Compares .bak files against their original counterparts using diff.

Link

URL Testing1

cat endpoints.txt | xargs -n 1 -I {} curl -s -o /dev/null -w '%{http_code} %{url_effective}\n' {}

Checks the HTTP status code for a list of endpoints.

Link

User Cleanup1

cat terminated_staff.txt | xargs -I {} sh -c 'userdel {}; rm -rf /home/{}'

Removes user accounts and their home directories based on a list.

Link

Bulk Copy1

find . -name '*.conf' -print0 | xargs -0 -I {} cp --parents {} /backup/conf/

Copies files preserving their directory structure to a backup location.

Link

Metadata Stripping1

find . -name '*.jpg' | xargs -n 1 mogrify -strip

Removes EXIF metadata from all JPG images in batch.

Link

Module Management1

cat modules.txt | xargs -n 1 modprobe

Loads a list of kernel modules.

Link

System Updates1

apt list --upgradable 2>/dev/null | cut -d/ -f1 | xargs apt-get install -y

Extracts upgradable package names and pipes them to the install command.

Link

Empty File Cleanup1

find . -type f -size 0 -print0 | xargs -0 rm

Removes all files with zero bytes size safely.

Link

Log Rotation Simulation1

find /var/log -name '*.log' | xargs -I {} mv {} {}.old

Renames all active log files to an archived extension.

Link

Certificate Auditing1

find /etc/ssl -name '*.pem' | xargs -I {} openssl x509 -in {} -noout -enddate

Checks the expiration date of all SSL certificates found in the directory.

Link

Threat Hunting1

find /tmp -user root -print0 | xargs -0 ls -la

Inspects files owned by root in temporary directories which may indicate compromise.

Link

Immutable Files1

find . -name 'important.txt' | xargs chattr +i

Sets the immutable flag on specific files to prevent deletion or modification.

Link

Container Cleanup1

docker ps -a -f status=exited -q | xargs -r docker rm

Removes only Docker containers that have exited.

Link

Orphaned Images1

docker images -f dangling=true -q | xargs -r docker rmi

Deletes dangling Docker images that are not tagged.

Link

Text Transformation1

cat words.txt | xargs -n 1 | sort | uniq

Normalizes a text file into a sorted list of unique words.

Link

Variable Construction1

ls | xargs | sed 's/ /,/g'

Converts a list of files into a comma-separated string suitable for arrays.

Link

Mass Creation1

seq 1 100 | xargs -I {} touch file_{}.txt

Rapidly creates 100 dummy files with sequential naming.

Link

Wait Handling1

seq 5 | xargs -n 1 -I {} sh -c 'sleep 1; echo waited {}'

Introduces a delay between the execution of each command.

Link

Recursive Ownership1

find /var/www -type d -print0 | xargs -0 chown www-data:www-data

Changes ownership of all directories in a tree safely.

Link

System Auditing1

find /bin -type f -ctime -1 | xargs ls -l

Identifies system binaries that have been changed in the last 24 hours.

Link

Config Validation1

find /etc/nginx -name '*.conf' | xargs -n 1 nginx -t -c

Validates the syntax of individual Nginx configuration files.

Link

Checksum Validation1

cat checksums.sha256 | xargs -n 2 sh -c 'echo "$1  $2" | sha256sum -c -'

Verifies file integrity using a list of checksums and filenames.

Link

Log Search Parallel1

find /var/log -type f | xargs -P 4 grep 'ERROR'

Greps through logs in parallel to speed up error finding.

Link

IP Blocking (Simulated)1

cat blacklisted_ips.txt | xargs -I {} iptables -A INPUT -s {} -j DROP

Adds firewall rules to drop traffic from a list of IP addresses.

Link

Key Rotation1

cat keys.txt | xargs -I {} aws kms schedule-key-deletion --key-id {}

Schedules a list of AWS KMS keys for deletion.

Link

JSON Parsing1

cat data.json | jq -r '.[] .id' | xargs echo IDs:

Extracts IDs from a JSON file and formats them into a single line.

Link

Kubernetes Logs1

kubectl get pods -l app=web -o name | xargs -n 1 -P 3 kubectl logs

Fetches logs from multiple pods matching a label in parallel.

Link

Advanced Arg File1

xargs -a params.txt -L 1 command

Reads arguments from a file line-by-line without using pipes.

Link

Shell Injection Defense1

ls | xargs -I {} bash -c 'echo "$1"' -- {}

Passes arguments to a subshell securely using positional parameters.

Link

High Volume Deletion1

find . -name 'temp*' -print0 | xargs -0 -n 1000 rm

Deletes huge numbers of files in batches of 1000 to avoid argument list too long errors.

Link

Dynamic Parallelism1

seq 100 | xargs -P $(nproc) -n 1 echo

Dynamically sets the number of parallel processes based on available CPU cores.

Link

File Locking1

find . -name '*.db' | xargs -I {} flock {} echo 'Locked {}'

Uses flock to ensure exclusive access to files before processing.

Link

Final Cleanup1

find . -maxdepth 1 -name 'xargs_test*' -print0 | xargs -0 -p rm

Safely prompts to clean up any test files created during this workflow session.

Link