Explaining “08: value too great for base (error token is “08”)” in Bash
The aim of this page📝 is to explain the issue of octal interpretation in bash scripts when dealing with numbers containing leading zeros, using a specific example of calculating week numbers.
2 min readFeb 23, 2024
- By default, bash interprets numbers with leading zeros as octal numbers.
- Octal numbers only use digits from 0 to 7, causing issues with numbers like 08 or 09.
- Using
10#
before a variable explicitly specifies decimal interpretation, avoiding octal errors.
History:
- The octal interpretation behavior in bash is inherited from the C programming language.
- Octal numbers were commonly used in early computing due to their compact representation.
Risks:
- Incorrectly interpreting numbers as octal can lead to unexpected results in calculations.
- It can be a common source of errors when handling numerical data in bash scripts.
Example code snippets:
# Original command causing error
next_CW=$((CW + 1))
# Corrected command using 10# to specify decimal interpretation
next_CW=$((10#$CW + 1))
`week`
- I have this short
week
function that gives me this/next week snippet I put in tickets sometimes - It broke on week 8 with
bash: 08: value too great for base (error token is "08")
function week() {
CW=$(date +%V)
year=$(date +%Y)
next_CW=$((10#$CW + 1)) #BEFORE: this was next_CW=$(($CW + 1))
if [ "$1" == "." ]; then
echo "---CURRENT WEEK---"
start_date=$(date -j -f "%Y %V" "$year $CW" "+%Y-%m-%d")
echo "(CW $CW commencing $start_date)"
this_week_eta="The work is scheduled for this week (CW $CW commencing $start_date)"
echo "$this_week_eta"
echo "$this_week_eta" | pbcopy
echo "~~~> MrD: clipping OK!"
elif [ "$1" == "+" ]; then
start_date=$(date -j -f "%Y %V" "$year $next_CW" "+%Y-%m-%d")
echo "---NEXT WEEK---"
echo "(CW $next_CW commencing $start_date)"
next_week_eta="The work is scheduled for the next week (CW $next_CW commencing $start_date)"
echo "$next_week_eta"
echo "$next_week_eta" | pbcopy
echo "~~~> MrD: clipping OK!"
fi
}
ANKI
Question:
What is the default behavior of bash when dealing with numbers containing leading zeros?
Answer:
Bash interprets numbers with leading zeros as octal by default.
Question:
How can you avoid octal interpretation issues in bash?
Answer:
You can use the syntax `10#` before a variable to explicitly specify decimal interpretation.