Reputation: 71
I've been getting the error: line 9: * 12: syntax error: operand expected (error token is "* 12")
(I entered 3, 4, 1 as a test on the script) the result that I need still shows at the end but after this error line. Why is that line showing if everything "works"?
Here's my code so you can understand what I did:
y='1'
z='0'
while [ $z = 0 ]
do
read x
if [[ "$x" -ge "0" ]];
then
y=$[$x*$y]
fi
done
echo -n "The multiplication of positive numbers entered is: $y"
exit
Upvotes: 0
Views: 1614
Reputation: 124646
line 9: * 12: syntax error: operand expected (error token is "* 12")
How is this possible?
The message is trying to tell you that an operand is expected,
but it wasn't there.
As an additional hint, the error token is * 12
.
Look closely where this might be.
This happens in the expression $x*$y
.
For example if x
is 2, and y
is 12,
then the expression is 2 * 12
.
But if the value of x
is the empty string,
then the expression is * 12
, that is,
nothing multiplied by 12.
That makes no sense, hence the error.
When x
has no value (you entered a blank line),
you probably want to break out of the loop:
while [ $z = 0 ]; do
read x
[[ $x ]] || break
if [[ "$x" -ge "0" ]]; then
y=$[$x*$y]
fi
done
In addition,
as @mklement0 pointed out in a comment,
the $[...]
syntax is obsoleted in favor of $((...))
,
and there's no good reason to mix [...]
and [[...]]
style conditionals.
Here's a more modern, cleaner version of your script,
also with the unused z
variable eliminated:
while true; do
read x
[[ $x ]] || break
if ((x >= 0)); then
((y = x * y))
fi
done
Upvotes: 2
Reputation: 241838
How do you end the input? If you entered Ctrl + d or an empty string, x was emtpy, and the shell tried to assign
y=$[*12]
Hence the error. I don't see why the loop ends in such a case, though, as $z
never changes.
Upvotes: 2
Reputation: 74605
The syntax of this line isn't correct:
y=$[$x*$y]
To assign the result of $x * $y
to $y
, use this:
y=$(( x * y ))
Remember that the shell only supports integer arithmetic.
Upvotes: 0