erratic sh arithmetic

Gary Aitken ubuntu at dreamchaser.org
Fri Jul 10 15:17:29 UTC 2020


On 7/10/20 12:33 AM, Karl Auer wrote:
> On Fri, 2020-07-10 at 08:25 +0200, Heinrich Bjerregaard via ubuntu- 
> users wrote:
>>> The digits 8 and 9 are not valid for octal numbers so just
>>> remove the leading zeros…
> 
> Except that the error the OP is getting is not the error you get
> when you use non-octal digits after a leading zero...

Interestingly, that is exactly the cause of the error:

$ cat tst_2.sh
#!/bin/sh

day=08
echo "day: " $day
dow=3
echo "dow: " $dow
week=`expr \( $day + 6 - $dow \) / 7 + 1`
echo "week: " $week
week=$(( ( $day + 6 - $dow ) / 7 + 1 ))
echo "week: " $week

$ ./tst_2.sh
day:  08
dow:  3
week:  2
./tst_2.sh: 9: ./tst_2.sh: arithmetic expression: expecting ')': " ( 08 + 6 - 3 ) / 7 + 1 "

Fixing the leading zero corrects the problem, either by removing the leading
zero or using a valid octal number.  It worked previously because the digits
were valid octal.  Thanks.

On 7/9/20 10:19 PM, Karl Auer wrote:

> Haven't looked closely, but any value beginning with "0" is regarded as
> octal, so 08 (also 09, 18, 19, 28 and 29) should be throwing "value too
> great for base".

> If it's been up for two weeks, running daily, you should have had a
> similar error on 28 and 29 June.

As I recall, those failed also and caused me to try expr, which worked;
but then I did a sanity check and retried the old form and it worked
(because the day was now legal octal), which caused craziness inside
my head.

> week=`expr \( 08 + 6 - 3 \) / 7 + 1`
> 
> works for me too, which I have to say was a bit of a surprise, I
> expected expr to understand octal, and my doco for expr says it does
> too. But this returns 3; if it understood octal it would return 2:
> 
> week=`expr \( "011" + 6 - 3 \) / 7 + 1`

strange; thanks again

Gary




More information about the ubuntu-users mailing list