Saturday, August 04, 2012

bash error: value too great for base

I came across this interesting error today:
-bash: 08: value too great for base (error token is "08")
It was coming from a script which works out the previous month by extracting the current month from the current date and then decrementing it. The code looks like this:
today="$(date +%Y%m%d)"
month=${today:4:2}
prevmonth=$((--month))
This script throws an error only if the current month is 08 or 09. I found that the reason for this is that numbers starting with 0 are interpreted as octal numbers and 8 and 9 are not in the base-8 number system, hence the error. There are more details on the bash man page:
Constants with a leading 0 are interpreted as octal numbers. A leading 0x or 0X denotes hexadecimal. Otherwise, numbers take the form [base#]n, where base is a decimal number between 2 and 64 represent- ing the arithmetic base, and n is a number in that base. If base# is omitted, then base 10 is used.
To fix this issue, I specified the base-10 prefix as shown below:
today="$(date +%Y%m%d)"
month=10#${today:4:2}
prevmonth=$((--month))

No comments:

Post a Comment