2

I'm having a small problem with this following snippet and I'm not sure why. The error given is (line indicated):

*2: syntax error: operand expected (error token is "*2")

while [[ $numberServers -gt $newindex ]]; do
    serverPort=$((9001+$(($newindex*2))))      <--- This line
    clientPort=$(($serverPort+1))
    newindex=$(($newindex+1))
    localhostport=$((serverPort-2))

    string=$(($string,localhost:$(($serverPort-2))))
...

Any help would be greatly appreciated.

7
  • Sounds like $newindex didn't have the value you were expecting. What value does it have? Commented Nov 20, 2015 at 18:28
  • It does look as if $newindex is empty. You should probably test that it has a value before you use it in a formula. Also, too many parentheses! serverPort=$((9001+$newindex*2)) should do exactly the same thing. Similarly, newindex=$(($newindex+1)) can be replaced with ((newindex++)). Commented Nov 20, 2015 at 18:35
  • 1
    You're also misusing arithmetic expressions in the last line; presumably, you want to append the string localhost:$(($serverPort-2)) to the end of string. Commented Nov 20, 2015 at 18:46
  • @chepner How do you mean? I am now getting an error on that line so I agree, I just can't see how/where I am misusing the arithmetic? Commented Nov 20, 2015 at 19:15
  • I assume you want string="$string,localhost:$localhostport" or string+=",locahost:$localhostport". At best, $(($string,localhost:$locahostport)) would evaluate $string, discard the result, and evaluate to the next string. But arithmetic expressions are for just that: arithmetic, not string handling. Neither argument of the , operator is an arithmetic expression. Commented Nov 20, 2015 at 19:17

1 Answer 1

3

The problem is that the variable newindex is empty, so the expression became:

$((9001+$((*2))))

check the initialization of newindex.

Example:

$ echo $((9001+$(($newindex*2))))
bash: *2: syntax error: operand expected (error token is "*2")

$ newindex=4

$ echo $((9001+$(($newindex*2))))
9009
Sign up to request clarification or add additional context in comments.

6 Comments

Thank you! Silly mistake really. But now I'm getting another error? line 26: ,localhost:9001: syntax error: operand expected (error token is ",localhost:9001")
@CAFC_Sam no problem..that seems like an syntax error..hard to tell without seeing the problematic line i.e. line 26..
line 26 is just string=$(($string,localhost:$(($serverPort-2))))
@CAFC_Sam now string is empty..also its unclear to me what you are doing here ..
I have initialised string. I'm trying to just loop through a set of port numbers and add them all to the end of string, ready for a command line argument to a Java program
|

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.