检查bash变量是否等于0 [英] Check if bash variable equals 0
问题描述
我有一个bash变量深度,我想测试它是否等于0.如果是的话,我想停止执行脚本.到目前为止,我有:
I have a bash variable depth and I would like to test if it equals 0. In case yes, I want to stop executing of script. So far I have:
zero=0;
if [ $depth -eq $zero ]; then
echo "false";
exit;
fi
不幸的是,这导致:
[: -eq: unary operator expected
(由于翻译可能不准确)
(might be a bit inaccurate due to translation)
请,我如何修改脚本以使其正常工作?
Please, how can I modify my script to get it working?
推荐答案
好像未设置您的depth
变量.这意味着在bash将变量的值代入表达式后,表达式[ $depth -eq $zero ]
变为[ -eq 0 ]
.这里的问题是-eq
运算符被错误地用作仅具有一个参数(零)的运算符,但是它需要两个参数.这就是为什么您收到一元运算符错误消息的原因.
Looks like your depth
variable is unset. This means that the expression [ $depth -eq $zero ]
becomes [ -eq 0 ]
after bash substitutes the values of the variables into the expression. The problem here is that the -eq
operator is incorrectly used as an operator with only one argument (the zero), but it requires two arguments. That is why you get the unary operator error message.
正如 Doktor J 在对此答案的评论中提到的,避免检查中未设置变量的问题的安全方法是将变量包含在""
中.请参阅他的评论以获取解释.
As Doktor J mentioned in his comment to this answer, a safe way to avoid problems with unset variables in checks is to enclose the variables in ""
. See his comment for the explanation.
if [ "$depth" -eq "0" ]; then
echo "false";
exit;
fi
与[
命令一起使用的未设置变量对bash来说是空的.您可以使用以下测试来验证这一点,因为xyz
为空或未设置,因此所有测试均评估为true
:
An unset variable used with the [
command appears empty to bash. You can verify this using the below tests which all evaluate to true
because xyz
is either empty or unset:
-
if [ -z ] ; then echo "true"; else echo "false"; fi
-
xyz=""; if [ -z "$xyz" ] ; then echo "true"; else echo "false"; fi
-
unset xyz; if [ -z "$xyz" ] ; then echo "true"; else echo "false"; fi
if [ -z ] ; then echo "true"; else echo "false"; fi
xyz=""; if [ -z "$xyz" ] ; then echo "true"; else echo "false"; fi
unset xyz; if [ -z "$xyz" ] ; then echo "true"; else echo "false"; fi
这篇关于检查bash变量是否等于0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!