Monday, January 27, 2014

leading zero, base 8

value too great for base (error token is XX)

When processing strings to numbers, eg, date +%S gives seconds, the output of "08", "09", will cause errors when used in an expression, because they are treated as base 8 (octal).

For example 60 - 08 will error as above. Nos 00 to 07 are also octal, but of course don't error and are the same as decimal, and 10 is treated as decimal 10. Only numbers with leading zero are octal. This string to number bug has caught some excellent shell script authors I know, usually when processing the output of date to do maths on dates and times. These scripts usually go wrong around August and September.

Tell BASH this is decimal with 10# prefix, 60 - 10#08

eg; wait until the next minute tick with:

sSec=$(date +%S); sWait=$(( 60 - 10#$sSec )); echo ${sSec} ${sWait}; sleep ${sWait}; date

sSec will be 08
sWait becomes 60-10#08, or 52 second sleep.

No comments:

Post a Comment