1. 程式人生 > >Linux 底下 檔案過多導致 ls 命令出現 arguments too long 的問題

Linux 底下 檔案過多導致 ls 命令出現 arguments too long 的問題

作為一個linux使用者/系統管理員, 有些時候你會遇到以下錯誤提示:

[[email protected] foo]$ mv * ../foo2

bash: /bin/mv: Argument list too long

“Argument list too long”引數列表過長錯誤經常發生在使用者在一行簡單命令中提供了過多的引數而導致,經常在ls *, cp *, rm * 等中出現。
根據問題的原因以下提供了四種方法,可以根據自己的情況酌情選用

方法1 : 將檔案群手動劃分為比較小的組合
e.g 1:

[[email protected] foo]$ mv [a-l]

* ../foo2

[[email protected] foo]$ mv [m-z]* ../foo2

這是最基本的方法,只是簡單的使引數數量符合要求,這種方法應用範圍有限,只適用於檔案列表中的名字分佈比較均勻,另外這也是個初級使用者可以考慮的解決方案,不過需要很多重複命令和對檔名分佈的觀察與猜測。

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

[[email protected] 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 {} /;

。。。。。。。。