Home > Software engineering >  "operand expected" in bash script
"operand expected" in bash script

Time:12-16

#!/bin/bash

echo 'Users for system Alderaan: '
read 'Ald'
echo 'Users for system Coruscant: '
read 'Cor'
echo 'Users for system Endor: '
read 'End'
echo 'Users for system Hoth: '
read 'Hot'
echo 'Users for system Tatooine: '
read 'Tat'

echo SUM=$(($Ald   $Cor   $End   $Hot   $Tat))
echo AVG=$(($SUM / 5))
Users for system Alderaan: 
4
Users for system Coruscant: 
4
Users for system Endor: 
4
Users for system Hoth: 
4
Users for system Tatooine: 
4
SUM=20
./starwars: line 15: / 5: syntax error: operand expected (error token is "/ 5")

I've tried a few different ways for the "5" but I can't seem to figure it out.

CodePudding user response:

The problem is that this line ...

echo SUM=$(($Ald   $Cor   $End   $Hot   $Tat))

... does not contain an assignment to SUM. It just prints output that resembles a shell assignment. Therefore, on the next line ...

echo AVG=$(($SUM / 5))

... $SUM expands to nothing, leaving you attempting to evaluate "/ 5" as an arithmetic expression.

Try this instead:

SUM=$(($Ald   $Cor   $End   $Hot   $Tat))
echo SUM=$SUM
echo AVG=$(($SUM / 5))

And note that there is no assignment to AVG, either, but that doesn't matter because you are not attempting to use any such variable.

CodePudding user response:

You're never setting the SUM variable. You're printing out (echo) a command which would set the SUM variable if you were to run that command, but you're not running that command, just printing it.

echo <... something ...>

will just print <... something ...>, it won't actually run <... something ...>. To run <... something ...> literally just put

<... something ...>
  • Related