2017-02-16 32 views
1

在Linux中,您可以執行簡單的命令行條件,例如。是否可以合併兩個Linux條件?

echo 'The short brown fox' | grep -q 'fox' && echo 'Found' || echo 'Not Found' 

>> Found 

或者

test -e test.txt && echo 'File Exists' || echo 'File Not Found' 
>> File exists 

是否有可能兩個條件結合成一個?所以如果找到了狐狸,我們會查看該文件是否存在,然後相應地執行該條件。

我曾嘗試以下,他們似乎並沒有工作:

echo 'The short brown fox' | grep -q 'fox' && (test -e test.txt && echo 'File Exists' || echo 'File Not Found') || echo 'Fox Not Found' 

echo 'The short brown fox' | grep -q 'fox' && `test -e test.txt && echo 'File Exists' || echo 'File Not Found'` || echo 'Fox Not Found' 

我需要的命令,發生在同一行。

回答

2

可以使用{ ...; }到組多個命令在殼這樣的:

echo 'The short brown fox' | grep -q 'fox' && 
{ [[ -e test.txt ]] && echo "file exists" || echo 'File Not Found'; } || echo 'Not Found' 

命令的所有大括號即{ ...; }將被執行內部時grep成功並||{ ...; }grep失敗評價。


編輯:

這裏是csh一個襯墊做相同的:

echo 'The short brown ox' | grep -q 'fox' && ([ -e "test.txt" ] && echo "file exists" || echo 'File Not Found' ;) || echo 'Not Found' 
+0

這只是顯示錯誤:{:命令未找到。 未找到文件 }:未找到命令。 找不到 – difurious

+0

你用的是什麼外殼?這對'bash'我很好# – anubhava

+0

我正在使用-csh – difurious

0

是啊!您可以使用AND和OR運算這樣的:

echo "The short brown fox" | grep fox && echo found || echo not found 

如果要抑制grep輸出,以及讓你只看到「發現」或「未找到」,你可以這樣做:

echo "The short brown fox" | grep fox >/dev/null && echo found || echo not found 

&&操作者和||操作符是短路,因此,如果返回echo "The short brown fox" | grep fox >/dev/null一個truthy退出代碼(0),則echo found將執行,並且由於也返回的退出代碼0時,echo not found永遠不會執行。

同樣,如果echo "The short brown fox" | grep fox >/dev/null返回falsey退出碼(> 0),那麼echo found根本不會執行,並且echo not found將執行。

2

請勿混用||&&這樣;使用明確的if語句。

if echo 'The short brown fox' | grep -q 'fox'; then 
    if test -e test.txt; then 
     echo "File found" 
    else 
     echo "File not found" 
    fi 
else 
    echo "Not found" 
fi 

a && b || c是不等價的,如果a成功和失敗b(雖然你可以使用a && { b || c; },但if說法更具有可讀性)。

+1

雖然這不能在一行上運行。 – difurious

+0

當然可以; '如果...;那麼如果......;然後回聲;其他;回聲;網絡連接;其他回聲; fi'。但是,你想要一個簡短的命令還是一個* correct *命令?幾乎在任何你在shell中看到換行符的地方,都可以用分號替換它。 – chepner

+0

只要注意到標籤中'csh'的改變。不知道這個答案是否仍然適用,但有很多理由從'csh'切換到'bash'(或者至少與POSIX相關的東西)。 – chepner

相關問題