Integer comparison in bash

I need to implement something like:

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

But I get

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

What am I doing wrong?

+4
source share
4 answers

The command [ cannot process arithmetic inside its test. Change it to:

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

Edit: what @cebewee wrote is also true; you must put a space before closing ] . But only this will lead to another error: extra argument '-'

+8
source
  • ] must be a separate argument [ .
  • You assume you can do the math in [ .

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

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

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

Closing ] must be preceded by a space, ie write

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

Source: https://habr.com/ru/post/1343163/


All Articles