tourism
tourism

Reputation: 155

Error Value is too great for base in bash

The below bash script is written for finding the files which are modified with in the last T second where T is supplied from the command line.

if [ $# -ne 1 ]; then
    echo "Wrong number of argument"
    exit 1
fi

for f in *
do
    if [ -x "$f" ]; then
        currenttime=$(date | awk '{print $4}')
        modify=$(date -r "$f" | awk '{print $4}')
        d_c=${currenttime:0:2}
        m_c=${currenttime:3:2}
        s_c=${currenttime:6:2}
        d_m=${modify:0:2}
        m_m=${modify:3:2}
        s_m=${modify:6:2}
        let "1d_c *= 24"
        let "m_c *= 60"
        let "second_c = d_c+m_c+s_c"
            let "d_m *= 24"
        let "m_m *= 60"
        let "second_m=d_m+m_m+s_m"
        let "diff=second_c-second_m"
        if [ $diff -lt $1 ]; then
            echo $f
        fi
    fi
do

ne

But I am getting the below error in that.

./recent.sh: line 46: let: 09: value too great for base (error token is "09")
./recent.sh: line 47: let: 09: value too great for base (error token is "09")
./recent.sh: line 49: let: 09: value too great for base (error token is "09")

I know that this error is coming due to the large value in the variable and I have to make the variable decimal but I don't know how to do it in my case(inside the let command, how to make them decimal).

Upvotes: 1

Views: 2110

Answers (1)

ruakh
ruakh

Reputation: 183351

The problem is that 09, due to the leading 0, is interpreted as octal, whereas (as you've surmised) you need it to be interpreted as decimal.

To fix this, you need to bypass let's normal convert-variable-to-number process. Instead of writing, for example, this:

let "second_c = d_c+m_c+s_c"

you should write this:

let "second_c = 10#$d_c + 10#$m_c + 10#$s_c"

By prepending $, you're asking Bash to substitute in the variable-value as a string — so, for example, if d_c is 09, then 10#$d_c will be 10#09. The 10# prefix tells let that the number should be interpreted as base-10.


Actually, on second thought, it's probably best to do this when you initially populate these variables; for example:

d_c=$(( 10#${currenttime:0:2} ))

That way you don't have to do it everywhere that you use them. (And also, it puts any errors closer to their source, which makes debugging easier.)

Upvotes: 3

Related Questions