Leading 0s cause bash to interpret numbers in the wrong base

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the bash category.

Last Updated: 2024-10-12

I got sporadic errors with this script:

#!/usr/bin/env bash

minutes=$(date +%M)

if [[ $((minutes % 10)) -eq $starting_minute ]]; then
   my_cmd
fi

The errors said:

08: value too great for base (error token is "08")

This happened when I ran the script at 19.08, causing $minutes to be "08". The issue here is that bash tries to interpret 08 as an octal number, since it starts with a zero. However, only the digits 0-7 are allowed in octal - decimal 8 is octal 010. Hence 08 is not a valid number, and that's the reason for the error.

The workarond for this, given that the date command returns minutes with a leading 0, is to explictly give the base with 10#$var

if [[ $(( 10#$minutes % 10)) -eq $starting_minute ]]; then
   my_cmd
fi

Lessons

Resources