Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integer comparison in bash

Tags:

bash

shell

unix

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 I am doing wrong?

like image 340
lstipakov Avatar asked Dec 07 '22 22:12

lstipakov


2 Answers

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 must put a space in front of the closing ]. But, just doing that will result in yet another error: extra argument '-'

like image 111
pepoluan Avatar answered Jan 03 '23 21:01

pepoluan


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

    if [ $i -ne $(($hosts_count - 1)) ] ; then
    
like image 23
Ignacio Vazquez-Abrams Avatar answered Jan 03 '23 21:01

Ignacio Vazquez-Abrams