bash bash中的整数比较

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5258839/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 23:36:05  来源:igfitidea点击:

Integer comparison in bash

bashshellunix

提问by lstipakov

I need to implement something like:

我需要实现类似的东西:

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

But I get

但我得到

./installer.sh: line 124: [: missing `]'

./installer.sh: 第 124 行: [: 缺少`]'

What I am doing wrong?

我做错了什么?

回答by pepoluan

The command [can't handle arithmetics inside its test. Change it to:

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

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

Edit:what @cebewee wrote is also true; you mustput a space in front of the closing ]. But, just doing that will result in yet another error: extra argument '-'

编辑:@cebewee 写的也是真的;你必须在结束前留一个空格]。但是,这样做会导致另一个错误:extra argument '-'

回答by Ignacio Vazquez-Abrams

  1. The ]must be a separate argument to [.
  2. You're assuming you can do math in [.

    if [ $i -ne $(($hosts_count - 1)) ] ; then
    
  1. ]必须是一个单独的参数[
  2. 你假设你可以在[.

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

回答by Mark Edgar

In bash, you can avoid both [ ]and [[ ]]by using (( ))for purely arithmetic conditions:

在bash中,你可以同时避免[ ][[ ]]利用(( ))纯粹的算术条件:

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

回答by Lars Noschinski

The closing ]needs to be preceded by a space, i.e. write

结束前]需要加一个空格,即写

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