Linux下文件过多导致 ls 命令出现 arguments too long 的问题


作为一个linux用户/系统管理员, 有些时候你会遇到以下错误提示:

[user@localhost foo]$ mv * ../foo2

bash: /bin/mv: Argument list too long

“Argument list too long”参数列表过长错误经常发生在用户在一行简单命令中提供了过多的参数而导致,经常在ls *, cp *, rm * 等中出现。
根据问题的原因以下提供了四种方法,可以根据自己的情况酌情选用

方法1 : 将文件群手动划分为比较小的组合
e.g 1:

 [user@localhost foo]$ mv [a-l]* ../foo2

[user@localhost foo]$ mv [m-z]* ../foo2

这是最基本的方法,只是简单的使参数数量符合要求,这种方法应用范围有限,只适用于文件列表中的名字分布比较均匀,另外这也是个初级用户可以考虑的解决方案,不过需要很多重复命令和对文件名分布的观察与猜测。

方法2 : 使用find命令
e.g 2:

 [user@localhost foo]$ find $foo -type f -name '*' -exec mv {}$foo2/. \;
方法2通过find命令,将文件清单输出到mv命令,使其一次处理一个,这样就完全避免了过量参数的存在,另外通过不同的参数,可以指定除了名称以外的时间戳,权限,以及inode等匹配模式。
方法2的缺点在于比较耗费时间。

方法3 : 创建shell函数
e.g 3.1:

 function huge_mv ()
{whileread line1; do
mv foo/$line1 ../foo2
done
}
ls -1 foo/ | huge_mv
写一个shell函数并不涉及到某种程度的复杂性, 这种方法比方法1和方法2相比更加灵活。
下面我们来扩展一下例3.1 :
e.g 3.2:

 function huge_mv ()
{whileread line1; do
md5sum foo/$line1 >> ~/md5sums
ls -l foo/$line1 >> ~/backup_list
mv foo/$line1 ../foo2
done
}
ls -1 foo/ | huge_mv
关键词: Linux   find -exec

前言:最近几天使用find的高级功能,但执行到 -exec命令的时候总是提示错误

信息如下:“find: missing argument to `-ok' ”,花了点时间,研究了下帮助(man),终于是搞清楚了。

说明:find命令,配合-exec参数,可以对查询的文件进行进一步的操作,可以得到很多有用的功能,比如说文件包含特定字符串的查询等,要了解这个功能,最简单直接的就是看find命令帮助,列出

        -exec command ;
               Execute command; true if 0 status is returned.   All   following   arguments   to find are taken to be arguments to the command until an   argument   consisting of #;' is encountered.   The string {}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find.   Both of these constructions might need to be escaped (with a \') or quoted to   protect   them   from   expansion   by the shell.   The command is executed in the starting directory.

其实只要读懂这段话就理解了

废话少说,这里简单说明一下

-exec 参数后面跟的是 command命令,注意点如下:

command命令的终止,使用 ';' (分号)来判定,在后面必须有一个 ';'

'{}',使用{}来表示文件名,也就是find前面处理过程中过滤出来的文件,用于command命令进行处理

特别强调,对于不同的系统,直接使用分号可能会有不同的意义, 使用转义符 '\'在分号前明确说明,对于前面我们遇到的问题,主要就是这个原因引起的!

举例:

1.查询所有保护字符串“Hello”的文件

find / -exec grep "Hello" {} \;

2.删除所有临时文件

find / -name "*.tmp" -exec rm -f {} \;

相关内容