2013-04-24 56 views
0

我試圖使用if語句與grep爲了檢查某個文件中是否存在字符串。現在,grep聲明工作本身,但是當我運行它作爲if語句的一部分輸出爲:太多的論據如果聲明Bash

line 6: [: too many arguments 

我的代碼:

#!/bin/bash 

if [ $(grep -c "OutOfMemory" /my/path/to/domains/*/*/subdomains/*/logs/*.*) -ne 0 ];  
then 
    echo "String found" 

else 
    echo "String not found" 

fi 

如果使用更短​​的路徑嘗試,但它沒沒有幫助。

任何建議都會有所幫助。

謝謝

+0

使用'find'搜索的文件,然後找到的exec會幫助你給grep。然後將結果存儲在某個變量中並使用它。沒有回答。有很多例子 – abasu 2013-04-24 16:29:28

回答

3

的問題是,你的grep -c不會產生正確的輸出。

e.g,你可以得到多個文件:

$ grep -c "OutOfMemory" /my/path/to/domains/*/*/subdomains/*/logs/*.* 
/my/path/to/domains/a/b/subdomains/c/logs/my.log:1 
/my/path/to/domains/a/b/subdomains/c/logs/another.log:2 

if語句不能處理由grep返回的多行,所以它失敗too many arguments

如果你想看看是否有包含字符串「內存不足」的任何文件,而是執行此操作:

if grep -q "OutOfMemory" /my/path/to/domains/*/*/subdomains/*/logs/*.* 
then 
... 
+0

如果我正確理解你,這將違反第一個條件退出?感謝您快速回答btw。 – 2013-04-24 16:47:47

+0

不確定你的意思。它將grep所有的文件,然後返回一個退出代碼0(真),如果在任何一個字符串中找到,或者1(假)如果沒有找到。 if語句將使用此退出碼。 – dogbane 2013-04-24 16:55:47

+0

如果您的'grep'支持該標誌,您可以添加'-m 1'來確保'grep'在第一次匹配後返回。 – chepner 2013-04-24 17:03:26