Wednesday, March 5, 2008

Argument list too long

Some commands such as chmod, rm, and grep to name a few, can take multiple filenames as arguments rather than executing the command once per file. This can be very powerful and convenient, but there is a point at which the list of arguments actually becomes too long

There exists a command, xargs, that takes as input a list of items, and passes them individually as arguments to another command. Consider, for example, the following:

find . -name 'cgisess*' | xargs rm

What this does, in relation to the remove command, is it finds, by name (in this case anything beginning with cgisess) and executes the rm command on it. Which is different then building a list of items to remove, then removing them as is done normally with the rm command.

Further complications: Special characters in filenames
The "find | xargs rm" thing only worked correctly because none of the filenames involved had any spaces in them. If the filenames involved have spaces, you will need to do use find's "-print0" option in conjunction with xargs's "-0" option.

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

No comments: