純/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
你的情況2和情況3是相同的。 'foo ='將foo定義爲空字符串,就像'foo =「」'所做的一樣。 –