2016-02-26 26 views
2

/bin/sh如何區分空變量,未設置變量和不存在(未定義)變量。Posix shell:區分空變量和不存在變量

這裏有情況:

# Case 1: not existing 
echo "${foo}" 

# Case 2: unset 
foo= 
echo "${foo}" 

# Case 3: Empty 
foo="" 
echo "${foo}" 

現在我想檢查每個這樣的三種情況。 如果情況2和情況3實際上是相同的,那麼我必須至少能夠區分它們和情況1.

任何想法?

UPDATE 解決由於利瑪竇

這是怎樣的代碼看起來像:

#foo <-- not defined 
bar1= 
bar2="" 
bar3="a" 

if ! set | grep '^foo=' >/dev/null 2>&1; then 
    echo "foo does not exist" 
elif [ -z "${foo}" ]; then 
    echo "foo is empty" 
else 
    echo "foo has a value" 
fi 

if ! set | grep '^bar1=' >/dev/null 2>&1; then 
    echo "bar1 does not exist" 
elif [ -z "${bar1}" ]; then 
    echo "bar1 is empty" 
else 
    echo "bar1 has a value" 
fi 

if ! set | grep '^bar2=' >/dev/null 2>&1; then 
    echo "bar2 does not exist" 
elif [ -z "${bar2}" ]; then 
    echo "bar2 is empty" 
else 
    echo "bar2 has a value" 
fi 


if ! set | grep '^bar3=' >/dev/null 2>&1; then 
    echo "bar3 does not exist" 
elif [ -z "${bar3}" ]; then 
    echo "bar3 is empty" 
else 
    echo "bar3 has a value" 
fi 

而且結果:

foo does not exist 
bar1 is empty 
bar2 is empty 
bar3 has a value 
+0

你的情況2和情況3是相同的。 'foo ='將foo定義爲空字符串,就像'foo =「」'所做的一樣。 –

回答

0

您可以使用set

如果沒有指定選項或參數,則set應該在當前語言環境的排序順序中寫入所有shell變量的名稱和值。每個名稱,應在單獨一行開始,使用格式:

可以列出所有的變量(set)和grep爲您要檢查

set | grep '^foo=' 
+0

謝謝我會用一些例子更新我的問題 – lockdoc

+0

'function foo = bar {:; }'會在bash中欺騙這個,'bar = $'\ nfoo = nope''會在大多數其他shell中欺騙它。 –

1

變量名我不知道sh ,但在bashdash中,您可以對案例1和案例2/3做echo ${TEST:?Error}。從快速瀏覽wikibooks,它似乎也應該適用於Bourne shell。

可以在bash和破折號像這樣使用(使用$?以獲取錯誤代碼)

echo ${TEST:?"Error"} 
bash: TEST: Error 
[[email protected]:~/tmp/soTest] echo $? 
1 
[[email protected]:~/tmp/soTest] TEST2="ok" 
[[email protected]:~/tmp/soTest] echo ${TEST2:?"Error"} 
ok 
[[email protected]:~/tmp/soTest] echo $? 
0 
[[email protected]:~/tmp/soTest] dash 
$ echo ${TEST3:?"Error"}  
dash: 1: TEST3: Error 
$ TEST3=ok 
$ echo ${TEST3:?"Error"} 
ok 
+0

語法是POSIX,但它不會區分一個不存在的變量和一個空變量 – Matteo

+0

@Matteo我想用'$?'來編寫腳本,請參閱我的編輯。 –

+1

'$ {TEST:?Error}'不區分未定義和空白。 '$ {TEST?Error}'確實。 –

1

您可以使用$ {VAR?}語法,如果無功是取消設置和$拋出一個錯誤{var:?}在var未設置或爲空時拋出一個錯誤。舉一個具體的例子:

$ unset foo 
$ test -z "${foo?unset}" && echo foo is empty || echo foo is set to $foo 
-bash: foo: unset 
$ foo= 
$ test -z "${foo?unset}" && echo foo is empty || echo foo is set to $foo 
foo is empty 
$ foo=bar 
$ test -z "${foo?unset}" && echo foo is empty || echo foo is set to $foo 
foo is set to bar