在bash比较整数,一元运算符预期 [英] Compare integer in bash, unary operator expected

查看:149
本文介绍了在bash比较整数,一元运算符预期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下code给出

[:-ge:一元运算符预期。

[: -ge: unary operator expected

i=0

if [ $i -ge 2 ]
                then
                #some code
                fi

为什么?

推荐答案

您的问题从事实产生了 $ I 有一个空值当你的语句失败。 始终报价的变量进行比较时,如果有丝毫的机会,他们中的一个可能是空的,例如:

Your problem arises from the fact that $i has a blank value when your statement fails. Always quote your variables when performing comparisons if there is the slightest chance that one of them may be empty, e.g.:

if [ "$i" -ge 2 ] ; then
  ...
fi

这是因为壳如何处理变量。假设原来的例如:

This is because of how the shell treats variables. Assume the original example,

if [ $i -ge 2 ] ; then ...

这是执行code的特定线的时候,壳做的第一件事是替补的价值$ I ,就像你喜欢的编辑器的搜索&安培;替换的功能会。所以假设 $ I 为空,或者,更说明问题,假设 $ I 是一堆的空间!外壳将取代 $ I 如下:

The first thing that the shell does when executing that particular line of code is substitute the value of $i, just like your favorite editor's search & replace function would. So assume that $i is empty or, even more illustrative, assume that $i is a bunch of spaces! The shell will replace $i as follows:

if [     -ge 2 ] ; then ...

现在,变量替换完成,因为它无法看到任何东西理解到的留下了比较外壳收益和失败.... -gt 。然而,引用 $ I

if [ "$i" -ge 2 ] ; then ...

变成了:

if [ "    " -ge 2 ] ; then ...

外壳现在看到的双引号,而且知道你实际上是比较空白4比2,将跳过如果

您还可以指定为 $ I 如果 $ I 为空,如下默认值的选项

You also have the option of specifying a default value for $i if $i is blank, as follows:

if [ "${i:-0}" -ge 2 ] ; then ...

这将取代值0,而不是的$ I $ I 是不确定的。我仍然保持引号,因为再次,如果 $ I 就是一堆空白的话,根本不能算作的未定义的,它不会被取代0,你就会碰到问题再一次。

This will substitute the value 0 instead of $i is $i is undefined. I still maintain the quotes because, again, if $i is a bunch of blanks then it does not count as undefined, it will not be replaced with 0, and you will run into the problem once again.

请阅读这个当你有时间。外壳采用像对待许多一个黑盒子,但非常少,非常简单的规则下运行 - 一旦你知道什么那些规则(它们是变量在shell如何工作之一,如上所述)外壳将没有更多的秘密你。

Please read this when you have the time. The shell is treated like a black box by many, but it operates with very few and very simple rules - once you are aware of what those rules are (one of them being how variables work in the shell, as explained above) the shell will have no more secrets for you.

这篇关于在bash比较整数,一元运算符预期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆