13

I have the following logic in my bash script:

#!/bin/bash
local_time=$(date +%H%M)

if (( ( local_time > 1430  && local_time < 2230 ) || ( local_time > 0300 && local_time < 0430 ) )); then
 # do something
fi

Every now and then, I get the error specified in the title (any time above 08xx appears to trigger the error).

Any suggestions on how to fix this?

I am running on Ubuntu 10.04 LTS

[Edit]

I modified the script as suggested by SiegeX, and now, I am getting the error: [: 10#0910: integer expression expected.

Any help?

jww
  • 97,681
  • 90
  • 411
  • 885
oompahloompah
  • 9,087
  • 19
  • 62
  • 90

3 Answers3

17

bash is treating your numbers as octal because of the leading zero

From man bash

Constants with a leading 0 are interpreted as octal numbers. A leading 0x or 0X denotes hexadecimal. Otherwise, numbers take the form [base#]n, where base is a decimal number between 2 and 64 represent- ing the arithmetic base, and n is a number in that base. If base# is omitted, then base 10 is used.

To fix it, specify the base-10 prefix

#!/bin/bash
local_time="10#$(date +%H%M)"

if (( ( local_time > 1430  && local_time < 2230 ) || ( local_time > 0300 && local_time < 0430 ) )); then
 # do something
fi
SiegeX
  • 135,741
  • 24
  • 144
  • 154
  • I modified my script as you suggested, and run it a few minutes ago, and I received the following error: [: 10#0910: integer expression expected – oompahloompah Mar 28 '11 at 08:23
  • @oompah: hmm, no error when I run it here or on ideone as listed [HERE](http://ideone.com/EaR6j). What version of `bash` are you using? – SiegeX Mar 28 '11 at 08:34
  • my bash version details are: GNU bash, version 4.1.5(1)-release (x86_64-pc-linux-gnu) – oompahloompah Mar 28 '11 at 08:37
  • @oompa: I don't know what to tell you. Did you *copy & paste* my code exactly and try to run it? Replace `# do something` with a simple `echo foo` to make sure its not the code you didn't paste – SiegeX Mar 28 '11 at 09:03
  • 1
    Thanks. I have used `"10$f"` for a `$f` variable and it works fine. – Wok Nov 05 '13 at 13:24
4

Following the advice from this blog, this works:

#!/bin/bash
local_time=`date +%H%M`
local_time="$(( 10#$local_time ))"

if (( ( local_time > 1430  && local_time < 2230 ) || ( local_time > 0300 && local_time < 0430 ) )); then
    echo "it is time!"
fi
lambmj
  • 1,843
  • 2
  • 21
  • 27
1

Solving the issue within the conditional test

One may be forced to keep the variable as it is for a variety of reasons (e.g. file naming issues). If this is the case, solve the issue within the conditional test by explicitly specifying base 10#:

#!/bin/bash
local_time=$(date +%H%M)

if (( ( 10#${local_time} > 1430  && 10#${local_time} < 2230 ) || ( 10#${local_time} > 0300 && 10#${local_time} < 0430 ) )); then
 # do something
fi
Serge Stroobandt
  • 28,495
  • 9
  • 107
  • 102