bug-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

doing simple math in bash :: prb with leading zero


From: ken
Subject: doing simple math in bash :: prb with leading zero
Date: Tue, 01 Sep 2009 10:33:17 -0400
User-agent: Thunderbird 2.0.0.0 (X11/20070326)

Doing very simple math in bash fails if a number begins with a zero (0).
 The short script below illustrates the problem:

----------------------- begin ------------------------

#!/bin/bash
#Testing number decrement because I ran into an errors
#e.g., lastmo=$((${lastmo}-1)) returns error:
# 09: value too great for base (error token is "09")
#This script assumes the month is September.

#Removing the initial '0' from $lastmo fixed the prb.

lastmo=$(date +%m) #shows current month as a number, e.g. "09"
echo The \"date\" command says the month is ${lastmo}

#Remove initial '0' so math in "else" below won't hork
#Uncomment the next 2 lines to fix error msg in "else" below.
#lastmo=${lastmo#0}
#echo After trimming initial zero, lastmo is $lastmo

year=$(date +%Y)
echo Immediately prior to \"if\" the current month is ${lastmo}

#Determine number representing previous month
if [ ${lastmo} -eq 1 ]
then
    lastmo=12
    year=$((${year} - 1))
else
        echo Before calc, lastmo = ${lastmo}
    lastmo=$((${lastmo}-1)) #doesn't work for "09"
#    lastmo=$((lastmo-=1)) #another way, same result
        echo After calc, lastmo = ${lastmo}
fi

#Just doing a comparison works okay for "09"
val1=$(date +%m)
echo Just doing a comparison using val1 when it is ${val1}

if [ ${val1} -eq 1 ]
then
        echo Values ${val1} and 1 are the same.
else
        echo Values ${val1} and 1 are different.
fi

if [ ${val1} -eq 9 ]
then
        echo Values ${val1} and 9 are the same.
else
        echo Values ${val1} and 9 are different.
fi



------------------------ end -------------------------

This is what I get on Linux running on an i686.

Bash should be smart enough to know that 09 = 9
-- and it does sometimes, but not all the time.
Surprise!!





reply via email to

[Prev in Thread] Current Thread [Next in Thread]