4

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?

4 Answers 4

8

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 '-'

Sign up to request clarification or add additional context in comments.

Comments

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

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

2 Comments

Thanks, but why I need to use double [[ ? @pepoluan answer also works, without double [[.
Well, you don't need to, but [[ will let you have unquoted empty variables without causing problems.
3

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

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

Comments

0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.