歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> Linux教程 >> Linux下文件過多導致 ls 命令出現 arguments too long 的問題

Linux下文件過多導致 ls 命令出現 arguments too long 的問題

日期:2017/2/28 16:12:06   编辑:Linux教程

作為一個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 {} \;

Copyright © Linux教程網 All Rights Reserved