2012-02-17 45 views
0

這是我的代碼如何簡化這個bash shell的代碼

if grep -q $lines scanHistory;then 
    echo -n '' 
else 
    if grep -q $lines waiting;then 
     echo -n '' 
    else 
     Download $lines 
     echo "---$lines was download successfully" 
    fi 
fi 

我purpoes是,如果$線不能在這兩個scanHistory被發現和等待,然後運行下載。

我不得不盡量讓這段代碼更simplily,如果作爲

如果grep的-qv $線scanHistory & & grep的-qv $排隊等待寫;然後

....

但failured ....

+0

和失敗的消息是......? – ariefbayu 2012-02-17 02:47:30

+3

而不是使用回聲作爲無操作,你可以使用:''' – 2012-02-17 02:54:24

+0

FWIW你也可以說'elif ... fi'而不是'else if ... fi; fi',但威廉Pursell有一個更好的答案。 – 2012-02-17 02:58:20

回答

5

嘗試:

 
if ! grep -q $lines scanHistory && ! grep -q $lines waiting; then ... 

用grep -v最初的嘗試失敗,因爲 的grep -v成功如果輸入的任何一行與模式不匹配。

+0

你可以將它壓縮到兩個文件的單個grep('if!grep -q $ lines scanHistory waiting; then ...'),但是在這種情況下,我會說這不太可讀,最好離開grep在他們周圍用明確的邏輯分開運行。 +1。 – 2012-02-17 04:17:45

1

也許你想

if ! (grep -q $lines scanHistory || grep -q $lines waiting) ; then 

    .... 

的問題是,-v不工作,你認爲它應該

當你grep nonexistant file,你得到1,沒有發現它的方式,但當grep -v nonexistant file返回代碼爲0時,因爲file中的所有其他行都是DID negative-match'nonexistant。

我希望這會有所幫助。

0
grep -q -e "$lines" scanHistory -e "$lines" waiting 
    if [ $? -ne 0 ] # Check if the above command is a success or not, if not run downlaod. 
    then 
     <run_Download> 
    fi 
0

使用bash短路運營商&&||

grep -q $lines scanHistory || 
    grep -q $lines waiting || 
    Download $lines && 
    echo "---$lines was download successfully" 

它可以放在單個行,如波紋管,但上述的可讀性:

grep -q $lines scanHistory || grep -q $lines waiting || Download $lines && echo "---$lines was download successfully"