2013-05-21 43 views
1

我發現this answer which works很好,但我想明白爲什麼下面的代碼不會檢測到兩個文件的存在?Bash,測試兩個文件的存在

if [[ $(test -e ./file1 && test -e ./file2) ]]; then 
    echo "yep" 
else 
    echo "nope" 
fi 

直接從殼作品運行此預期:

test -e ./file1 && test -e ./file2 && echo yes 
+0

您更新包含shell腳本反模式的一個很好的慷慨灑從http://partmaps.org/era/unix /award.html – tripleee

+0

使用您發現在交互式shell中工作的簡單,慣用,正確的代碼有什麼問題? 'test -e ./file1 && test -e ./file2 && echo yep || echo nope' – tripleee

+0

@tripleee非常感謝您對反模式的鏈接,我希望那些來這個問題的人會看看[編輯由chepner回覆](http://stackoverflow.com/posts/16674743/revisions)事實上,是的,寫一個荒謬的東西,但對於理解什麼是和不可能是非常有幫助的。關於你的問題,這是一個不適合交互式shell的較大腳本的一部分。 – AJP

回答

7

test -e ./file1 && test -e ./file2輸出是一個空字符串,這會導致[[ ]]以產生非零的退出代碼。你想

if [[ -e ./file1 && -e ./file2 ]]; then 
    echo "yep" 
else 
    echo "nope" 
fi 

[[ ... ]][ ... ]test ...的替代,而不是圍繞它的包裝。

5

if根據其返回值執行程序(或內置,在[[的情況下)和分支。您需要忽略無論是[[ ]]test S:

if [[ -e ./file1 && -e ./file2 ]]; then 

或者

if test -e ./file1 && test -e ./file2; then