2016-02-26 28 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