Bash shell scripting and octal values

August 9, 2009

linux

While rechecking my rdup test-suite one of the tests failed. On closer inspection it was due to the following line:

DAY_BEFORE=$(( $(date +%d) - 1 )) 

When $(date +%d) is 10 this yields:

$ DAY_BEFORE=$(( 10 - 1 ))
$ echo $DAY_BEFORE
9

Also with octal values (those starting with a leading zero), it also works:

$ DAY_BEFORE=$(( 06 - 1 )) 
$ echo $DAY_BEFORE
5

So when does this go wrong? When the day is 08 or 09 (as it is today):

$ DAY_BEFORE=$(( $(date +%d) - 1 ))
bash: 09: value too great for base (error token is "09")

My fix was not to let date generate the leading zero in the first place:

$ DAY_BEFORE=$(( $(date +%_d) - 1 ))
$ echo $DAY_BEFORE
8

Moral of the story:

Be careful with leading zeros in Bash, as they might get interpreted as octal values.

None