2016-09-30 63 views
0

我很困惑:功能/斌/在shell腳本錯誤做出否定的效果

#!/bin/sh 
[ -f /etc/init.d/functions ] && . /etc/init.d/functions 

[ 0 -eq 0 ] && action "Test" /bin/false || action "Test" /bin/true 

echo "###############" 

[ 0 -eq 0 ] && action "Test" /bin/true || action "Test" /bin/false 

結果是:

Test              [FAILED] 
Test              [ OK ] 
############### 
Test              [ OK ] 

不動作/斌/假函數返回錯誤值,使在||之後的聲明被執行? 如果我必須把/斌/假的「& &」塊,做

回答

1

的事情是:

action "Test" /bin/false 

回報1||後會導致命令來執行的失敗行動。 有效這種行爲是這樣的:

[ 0 -eq 0 ] && { action "Test" /bin/false || action "Test" /bin/true; } 

這是更多的理由來使用if/else/fi並得到正確的行爲:

echo "###############" 
if [ 0 -eq 0 ]; then 
    action "Test" /bin/false 
else 
    action "Test" /bin/true 
fi 

這將輸出:

Test              [FAILED] 
1

什麼自/斌/假返回FALSE,它通過||和返回/斌/真

看看它是這樣的:

true && false || true -> true 
true && true || false -> true 

如果使用

[ 0 -eq 0 ] && action "Test" /bin/false && action "Test" /bin/true 

如果將返回false,如你預期?

看到這個

#!/bin/bash 
[ 1 = 1 ] && echo "displayed because previous statement is true" 

[ 1 = 0 ] && echo "not shown because previous statement is false" 

[ 1 = 1 ] || echo "not shown because previous statement is true" 

[ 1 = 0 ] || echo "displayed because previous statement is false"