xargs - Linux


Overview

xargs is a powerful command used in Unix-like operating systems to build and execute command lines from standard input. This utility reads items from the standard input, delimited by blanks (which can be protected with double or single quotes or a backslash) or newlines, and executes the specified command using the read items as arguments. It is most effective for processing a list of files, generating commands from the output of another command, and handling large lists of arguments safely.

Syntax

The basic syntax of the xargs command is:

xargs [options] [command [initial-arguments]]
  • command is the command xargs executes. It’s optional; the default is /bin/echo.
  • initial-arguments are specified before the arguments that xargs passes from input.

Options/Flags

  • -0, –null: Input items are terminated by a null character instead of whitespace, useful with find -print0.
  • -d, –delimiter <delimiter>: Use specified delimiter instead of whitespace for input items.
  • -I <replace-str>: Replace occurrences of replace-str in the initial arguments with names read from input.
  • -L <max-lines>: Use at most max-lines non-blank input lines per command line.
  • -n <max-args>: Use at most max-args arguments per command line.
  • -p, –interactive: Prompt before running commands.
  • -r, –no-run-if-empty: Do not run the command if the input is empty.
  • -t, –verbose: Print the command line on the standard error before executing it.
  • -s <max-chars>: Limit the length of the command line to max-chars.

Examples

  1. Basic Usage: Print all filenames in a directory, one per line:
    ls | xargs -n 1 echo
    
  2. Using Null Character: Delete files whose names are listed in a file:
    cat list_of_files.txt | xargs -0 rm
    
  3. Interactive Deletion: Prompt user before deleting each file found by find:
    find /path/to/dir -type f -name "*.bak" -print | xargs -p rm
    
  4. Using Replacement String: Compiling multiple Java files listed in a file:
    cat java_files.txt | xargs -I {} javac {}
    

Common Issues

  • Argument List Too Long: Use the -n option to specify a smaller number of arguments per command line.
  • Handling Special Characters: Files with spaces, newlines, or special characters can cause issues. Use -0 with find -print0 to safely handle filenames with special characters.

Integration

xargs can be effectively combined with commands like find, grep, awk for powerful command pipelines:

  • Finding and Deleting Old Files:
    find /backup -mtime +30 -print0 | xargs -0 rm
    
  • Processing Git Branches:
    git branch | grep -v master | xargs -n 1 git branch -d
    
  • find: Generates a list of filenames and can pass them to xargs.
  • awk: Used for pattern scanning and processing, often piped into xargs.
  • grep: Searches for patterns and can output results piped into xargs.

For more detailed information, visit the official xargs documentation.