Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I am trying to debug someone else's script:

The code line is:

y=$((${oldvalue[$x]}-${newvalue[$x]}))

y gets calculated fine as long as both sides are positive numbers. However, I have a production situation where they are both negative and the error I get is:

DEBUG Old value = -4144290000
DEBUG New value = -4009685000
script.sh: line 123: -4144290000--4009685000: assignment requires lvalue

I never would use ksh myself for even the simplest of calculations but I am in a position of production support and have to deal with a big ball of mud, I would use at least Perl/Python. Can anybody tell why this problem is happening and how to fix it?

share|improve this question

2 Answers 2

up vote 5 down vote accepted

If you're using the $xxx syntax, then the variable is expanded, and then the result is evaluated as an arithmetic expression.

So,

y=$((${oldvalue[$x]}-${newvalue[$x]}))

Becomes

y=$((-4144290000--4009685000))

and ksh complains about that unexpected -- operator.

You can get around it by adding spaces as you found out, in which case it becomes:

y=$((-4144290000 - -4009685000))

But, you could also write it:

y=$((oldvalue[$x]-newvalue[$x])))

In that case, the content of the variable is expanded as part of the arithmetic evaluation and in that case as one numerical value.

The different becomes even more important in cases like:

a=1+1 b=2
echo "$((a*b)) vs $(($a*$b))"

Which gives 4 vs 3, and points to a third and more robust than the first way to work around the problem:

y=$(((${oldvalue[$x]}) - (${newvalue[$x]})))
share|improve this answer

It needed spaces on both sides of the minus:

y=$((${oldvalue[$x]} - ${newvalue[$x]}))
share|improve this answer
2  
Just to explain further, this is because -- was interpreted as a decrement operator. –  Random832 Dec 27 '12 at 20:40

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.