2014-04-22 60 views
1

我有以下功能打印我目前的IP:檢查輸出空

function get_ip 
    echo -n -s (ifconfig en1 | grep inet | grep -v inet6 | awk '{print $2}') 
end 

$ get_ip 
192.168.1.4~ 

我期待着打印offline如果get_ip返回任何(它打印「」當我離線) 。

我想:

if get_ip 
    echo "Yes" 
else 
    echo "No" 
end 

但它總是返回Yes

我該如何做到這一點?

回答

3

您需要檢查內置測試的退出狀態。

if test -n (get_ip) 
    echo Yes 
else 
    echo No 
end 

測試時,我發現-n-z,我會跟進之間的一些矛盾。試試這個:

if test -z (get_ip) 
    echo No 
else 
    echo Yes 
end 

this answer從魚的維護者,兩個答案都錯了,即使第二次作品之一。二者必選其一

count (get_ip); and echo Y; or echo N 

set result (get_ip) 
test -n "$result"; and echo Y; or echo N 
+0

它仍然總是返回'Yes'。 – jviotti

+0

謝謝,'test -z'就像一個魅力! – jviotti