What does value too great for base mean? (Octal values in arithmetic.)

When reading numbers from files or commands and then performing arithmetic with them, leading zeroes may cause a problem:

$ echo $((09))
bash: 09: value too great for base (error token is "09")

When a zero-padded value is used in a math context, the value is treated as octal (base 8). In the best cases, you actually get an error message, because 8 and 9 are invalid octal digits. In the worst cases, you won't notice the problem immediately, but the program will fail later.

This issue often occurs when reading time and date components, because they are commonly zero-padded to two digits (e.g. 08:11:42 as a time, or 2013-09-14 as a date).

There are two simple solutions to this issue: either remove the leading zeroes, or force bash to treat the values as decimal (base 10). Examples and explanations and some additional warnings are given on the arithmetic expression page.

It's also worth taking a moment to point out that when you read values from an external source and then attempt arithmetic with them, unwanted octal or hexadecimal interpretation is not the only problem you may encounter. A malicious user can also cause arbitrary code execution with specially crafted values.

$ a=42 b='x[$(date >&2)0]'
$ echo $((a + b))
Thu Apr 29 22:37:22 EDT 2021

It's important to perform basic input validation on numbers that come from untrusted sources. Make sure they're actually numbers before you use them. Trusted sources like the date(1) command with options like +%m or +%H are safe from code injection vulnerabilities, so you only need to worry about the leading zeroes in those cases.

BashFAQ/121 (last edited 2021-04-30 02:45:52 by GreyCat)