【Linux小笔记】用xargs处理Argument list too long的错误以及其原理

最近要删除 /tmp 底下的档案,下了 rm *.log 突然跳出 Argument list too long

这个错误,查了一下,原来是档案数量太多,超过Linux 允许作为 rm 参数的範围,而被报错了。

知道原因后,继续找了方法,查到可以用下面的语法来解决:

find . -name "*.log" | xargs rm

前面用 find 是不难理解,后面的 xargs 看上去就有点陌生了,查了一下 xargs的定义

NAME

xargs - build and execute command lines from standard input

DESCRIPTION

This manual page documents the GNU version of xargs. xargs 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 command (default is /bin/echo) one or more times with any initial-arguments followed by items read from standard input. Blank lines on the standard input are ignored.

Because Unix filenames can contain blanks and newlines, this default behaviour is often problematic; filenames containing blanks and/or newlines are incorrectly processed by xargs. In these situations it is better to use the -0 option, which prevents such problems. When using this option you will need to ensure that the program which produces the input for xargs also uses a null character as a separator. If that program is GNU find for example, the -print0 option does this for you.

If any invocation of the command exits with a status of 255, xargs will stop immediately without reading any further input. An error message is issued on stderr when this happens.

意思是说 xargs 可以把标準输入作为来源,然后执行它后面的命令。所以以上面的命令来说,它是将 find找到的结果,透过 pipeline 将输出转成输入,转给xargs使用。

不过即使如此,乍看之下也不知道这样和 rm *.log 有什么实际上的差别,为什么转一手给 xargs就不会跳出 Argument list too long ?

这个就要深入到 xargs 的原理了,在 你真的了解xargs命令吗 这篇文章中,深入去讨论 xargs 的运作方式,他作对上面 DESCRIPTION中:

executes the command (default is /bin/echo) one or more times

这段话,实际去验证究竟会执行几次,发现 xargs 使用的 命令一次会被调用 2000~ 4000次左右,因此,如果列出的log有一万笔的话,可能就会被分成 3到 5次左右来执行,因而避开了 Argument list too long 的错误。

在查询的过程中,也发现了一篇不错的文章 玩转 xargs 一起分享给邦友。如果邦友有什么使用 xargs 上的妙用,也欢迎分享给小弟知道。


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章