Value too great for base (error token is "08")

BashShell

Bash Problem Overview


Here my problem is to find the difference of using single bracket [ ] and double brackets [[ ]] in if statement.

#!/bin/bash
vara=08;
varb=10;

## single bracket in if statment is working.
if [ $vara -lt $varb ]; then
echo "yes";
else
echo "no";
fi


## double brackets in if statment is not working; throwing an error like below.
## [[: 08: value too great for base (error token is "08")
if [[ $vara -lt $varb ]]; then
echo "yes";
else
echo "no";
fi

Bash Solutions


Solution 1 - Bash

The shell tries to interpret 08 as an octal number, as it starts with a zero. Only digits 0-7 are, however, allowed in octal, as decimal 8 is octal 010. Hence 08 is not a valid number, and that's the reason for the error.

Single brackets are kind of "compatibility mode" with sh, and sh does not know about octal numbers.

So, if you use single square brackets, "010" will be interpreted as 10, while with double square brackets, "010" will be interpreted as 8.

If you use single square brackets, "08" will be interpreted as 8, while with double square brackets, it is not a valid number and leads to an error.

You can avoid the error by using the solution described here: https://stackoverflow.com/a/12821845/1419315

if [[ ${vara#0} -lt ${varb#0} ]]

or

if [[ $((10#$vara)) -lt $((10#$varb)) ]]

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionThaangarajView Question on Stackoverflow
Solution 1 - BashJohnBView Answer on Stackoverflow