2011-11-22 142 views
3

我知道我可以用-z測試一個字符串是否爲空,並用-n測試字符串是否爲非空。所以我寫在Ubuntu 10.10的腳本:bash空字符串比較問題

#!/bin/bash 
A= 
test -z $A && echo "A is empty" 
test -n $A && echo "A is non empty" 
test $A && echo "A is non empty" 

str="" 
test -z $str && echo "str is empty" 
test -n $str && echo "str is non empty" 
test $str && echo "str is non empty" 

令我驚訝的是,它的輸出:

A is empty 
A is non empty 
str is empty 
str is non empty 

我的事情應該是

A is empty 
str is empty 

可以在任何Linux的專家解釋,爲什麼?

謝謝。

回答

5

這是Bash命令行解析的結果。變量替換髮生在構造(基本)語法樹之前,因此-n運算符不會獲得一個空字符串作爲參數,它將獲得無參數!在一般情況下,你必須用任何變量引用到「」除非你能積極確保它不是空的,正是爲了避免這一點,類似的問題

5

'問題' 來源於此:

$ test -n && echo "Oh, this is echoed." 
Oh, this is echoed. 

test -n沒有參數返回0/OK。

修改成:

$ test -n "$A" && echo "A is non empty" 

,你會得到你所期望的結果。

2

這一個將工作:

#!/bin/bash 
A= 
test -z "$A" && echo "A is empty" 
test -n "$A" && echo "A is non empty" 
test $A && echo "A is non empty" 

str="" 
test -z "$str" && echo "str is empty" 
test -n "$str" && echo "str is non empty" 
test $str && echo "str is non empty" 

剛$ A或$ str作爲空字符串不會成爲測試的參數,然後測試狀態對於一個參數(非零長度的字符串)始終爲真。最後一行工作正常,因爲沒有參數的測試總是返回false。