I have been reviewing some useful commands in Linux during the holidays. Using the xargs command in Linux is one of them. Here are some sysadmin-style examples, simple and useful. Before, writing this I brewed coffee at home using my french press. Coffee inspires me.

The xargs command receives input from another command. In simple terms, it takes the output of one command and passes it as arguments to another command.

The logic behind the xargs command is:

stdin → xargs → command arguments

Delete many files safely using xargs

rm cannot handle huge lists from find. You can use the below find command and pass the arguments to the xargs command:

find /var/logs -name "*.log" | xargs rm -f
  • find outputs file names
  • xargs feeds them to rm
  • Files are removed (you need to be careful!)

If your files have spaces use this:

find /var/logs -name "*.log" -print0 | xargs -0 rm f
  • -print0 Handles unusual filenames: whitespaces, file name spaces or any other unusual characters.
  • xargs -0 → reads null-separated input

Check disk usage of many directories

ls /home/myusername/ | xargs -I{} du -sh /home/myusername/{}
  • Each directory becomes {}
  • du runs once per folder
  • Output stays readable

Restart services from a list

printf "nginx\nsshd\ncrond\n" | xargs systemctl restart
  • Each line becomes an argument
  • systemctl restarts all
  • One clean command

Other useful arguments used in xargs:

  • -n → limit arguments per command
  • -I{} → placeholder replacement
  • -0 → handle null-terminated input

Leave a comment

Your email address will not be published. Required fields are marked *