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
Integer comparison in bash
提问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
- The
]must be a separate argument to[. You're assuming you can do math in
[.if [ $i -ne $(($hosts_count - 1)) ] ; then
- 本
]必须是一个单独的参数[。 你假设你可以在
[.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

