2014-04-22 67 views
2

鑑於只有產生輸出給予一定的輸入該驅動程序功能之間的區別:測試命令:-n和-z

function driver -a arg 
    test $arg = 1; and echo OK 
    return 0 
end 

事情工作確定當函數發出輸出:

$ driver 1 | od -c 
0000000 O K \n 
0000003 
$ test -z (driver 1); and echo no output; or echo some output 
some output 
$ test -n (driver 1); and echo some output; or echo no output 
some output 

但在無輸出的情況下:

$ driver 0 | od -c 
0000000 
$ test -z (driver 0); and echo no output; or echo some output 
no output 
$ test -n (driver 0); and echo some output; or echo no output 
some output 

這是一個錯誤?

回答

6

這不是一個錯誤!

命令替換(driver X)執行驅動程序功能,然後將每個輸出行轉換爲參數。在(驅動程序0)的情況下,沒有輸出,所以你得到零個參數。所以無輸出的情況相當於運行test -ztest -n

好老IEEE 1003.1 tells us what test must do in this case

1論點:退出真(0)如果$ 1不是null;否則,退出虛假

所以當-n是唯一的參數,它失去了它的地位,作爲一個標誌,你剛剛結束了測試「-n」非無效(當然它傳遞)。

你可以看到在bash相同的行爲:

> test -n `echo -n` ; echo $? 
0 

在魚類中,如果你想檢查一個字符串是否非空,你可以使用count

if count (driver 0) > /dev/null 
    # output! 
end 

你可以還可以使用一箇中間變量與測試:

set -l tmp (driver 0) 
test -n "$tmp" ; and echo some output; or echo no output 

引號確保$ tmp總是成爲一個ar gument(可能是空的)。

+0

請注意,上述行爲可能會或可能不會很快發生變化:https://github.com/fish-shell/fish-shell/issues/4163 –