Fix "Argument list too long" issue when deleting file

Fix "Argument list too long" issue when deleting file

When deleting multiple files at once on one of my servers, I encountered a problem.

I got the error message Argument list too long when I tried to delete a large number of obsolete PHP session files.

This error message comes from the fact that the CLI limit has been reached (knowing that the star in the command takes every file).
When a folder contains several million files, the Linux kernel stops the command because the command is too long.
This problem can also occur on other commands that work like cp, such as cp, mv, etc.

The solution to get around this problem is to use the find and xargs command.

The find command allows you to find all files in a certain location, and xargs allows you to chain commands that take arguments as input.

The command below should therefore be entered:

Important: No confirmation will be requested to delete files or folders.
Be sure of what you are doing, even if it means doing an "echo" instead of the "rm" command.
sudo find LOCATION -name 'PATTERN' | sudo xargs rm

LOCATION is the location of the folder to search for, such as /var/log/
PATTERN is the pattern to search and take the files to delete, such as *.log

Errors will be displayed in the terminal or in the currently established SSH session.