bash中的整数比较

时间:2011-03-10 11:09:42

标签: bash shell unix

我需要实现类似的东西:

if [ $i -ne $hosts_count - 1] ; then
    cmd="$cmd;"
fi

但是我得到了

  

./ installer.sh:第124行:[:遗失   `]'

我做错了什么?

4 个答案:

答案 0 :(得分:8)

命令[无法在其测试中处理算术。将其更改为:

if [ $i -ne $((hosts_count-1)) ]; then

编辑: @cebewee所写的内容也是如此;您必须在结束]前放置一个空格。但是,这样做会导致另一个错误:extra argument '-'

答案 1 :(得分:4)

  1. ]必须是[的单独参数。
  2. 你假设你可以在[做数学。

    if [ $i -ne $(($hosts_count - 1)) ] ; then
    

答案 2 :(得分:3)

在bash中,您可以通过[ ]用于纯算术条件来避免[[ ]](( ))

if (( i != hosts_count - 1 )); then
  cmd="$cmd"
fi

答案 3 :(得分:0)

结束]需要以空格开头,即写

if [ $i -ne $hosts_count - 1 ] ; then
    cmd="$cmd;"
fi