在使用 find命令的-exec選項處理匹配到的文件時, find命令將所有匹配到的文件一起傳遞給exec執行。但有些系統對能夠傳遞給exec的命令長度有限制,這樣在find命令運行幾分鐘之后,就會出現溢出錯誤。錯誤信息通常是“參數列太長”或“參數列溢出”。這就是xargs命令的用處所在,特別是與find命令一起使用。
find命令把匹配到的文件傳遞給xargs命令,而xargs命令每次只獲取一部分文件而不是全部,不像-exec選項那樣。這樣它可以先處理最先獲取的一部分文件,然后是下一批,并如此繼續下去。
在有些系統中,使用-exec選項會為處理每一個匹配到的文件而發起一個相應的進程,并非將匹配到的文件全部作為參數一次執行;這樣在有些情況下就會出現進程過多,系統性能下降的問題,因而效率不高; 而使用xargs命令則只有一個進程。另外,在使用xargs命令時,究竟是一次獲取所有的參數,還是分批取得參數,以及每一次獲取參數的數目都會根據該命令的選項及系統內核中相應的可調參數來確定。
使用實例:
實例1: 查找系統中的每一個普通文件,然后使用xargs命令來測試它們分別屬于哪類文件
命令:
find . -type f -print | xargs file
輸出:
[root@localhost test]# ll總計 312-rw-r--r-- 1 root root 302108 11-03 06:19 log2012.log-rw-r--r-- 1 root root 0 11-12 22:25 log2013.log-rw-r--r-- 1 root root 0 11-12 22:25 log2014.logdrwxr-xr-x 6 root root 4096 10-27 01:58 scfdrwxrwxrwx 2 root root 4096 11-12 19:32 test3drwxrwxrwx 2 root root 4096 11-12 19:32 test4[root@localhost test]# find . -type f -print | xargs file./log2014.log: empty./log2013.log: empty./log2012.log: ASCII text[root@localhost test]#
實例2:在整個系統中查找內存信息轉儲文件(core dump) ,然后把結果保存到/tmp/core.log 文件中
命令:
find / -name "core" -print | xargs echo "" >/tmp/core.log
輸出:
[root@localhost test]# find / -name "core" -print | xargs echo "" >/tmp/core.log[root@localhost test]# cd /tmp[root@localhost tmp]# ll總計 16-rw-r--r-- 1 root root 1524 11-12 22:29 core.logdrwx------ 2 root root 4096 11-12 22:24 ssh-TzcZDx1766drwx------ 2 root root 4096 11-12 22:28 ssh-ykiRPk1815drwx------ 2 root root 4096 11-03 07:11 vmware-root
實例3:在當前目錄下查找所有用戶具有讀、寫和執行權限的文件,并收回相應的寫權限
命令:
find . -perm -7 -print | xargs chmod o-w
輸出:
[root@localhost test]# ll總計 312-rw-r--r-- 1 root root 302108 11-03 06:19 log2012.log-rw-r--r-- 1 root root 0 11-12 22:25 log2013.log-rw-r--r-- 1 root root 0 11-12 22:25 log2014.logdrwxr-xr-x 6 root root 4096 10-27 01:58 scfdrwxrwxrwx 2 root root 4096 11-12 19:32 test3drwxrwxrwx 2 root root 4096 11-12 19:32 test4[root@localhost test]# find . -perm -7 -print | xargs chmod o-w[root@localhost test]# ll總計 312-rw-r--r-- 1 root root 302108 11-03 06:19 log2012.log-rw-r--r-- 1 root root 0 11-12 22:25 log2013.log-rw-r--r-- 1 root root 0 11-12 22:25 log2014.logdrwxr-xr-x 6 root root 4096 10-27 01:58 scfdrwxrwxr-x 2 root root 4096 11-12 19:32 test3drwxrwxr-x 2 root root 4096 11-12 19:32 test4[root@localhost test]#
新聞熱點
疑難解答