Vicky Vicky - 6 months ago 206
Linux Question

Argument list too long error for rm, cp, mv commands

I have several hundred PDFs under a directory in UNIX. The names of the PDFs are really long (approx. 60 chars).

When I try to delete all PDFs together using the following command:

rm -f *.pdf


I get the following error:

/bin/rm: cannot execute [Argument list too long]


What is the solution to this error?
Does this error occur for
mv
and
cp
commands as well? If yes, how to solve for these commands?

Answer

The reason this occurs is because bash actually expands the asterisk to every matching file, producing a very long command line.

Try this:

find . -name "*.pdf" -print0 | xargs -0 rm

Warning: this is a recursive search and will find (and delete) files in subdirectories as well. Tack on -f to the rm command only if you sure you don't want confirmation.

If you're on Linux, you can do the following to make the command non-recursive:

find . -maxdepth 1 -name "*.pdf" -print0 | xargs -0 rm