Value too great for base (error token is “0925”)

后端 未结 3 704
盖世英雄少女心
盖世英雄少女心 2021-02-14 00:40

I have the following logic in my bash script:

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

if (( ( local_time > 1430  && local_time < 2230 ) || ( local_ti         


        
相关标签:
3条回答
  • 2021-02-14 01:05

    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
    
    0 讨论(0)
  • 2021-02-14 01:07

    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
    
    0 讨论(0)
  • 2021-02-14 01:08

    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
    
    0 讨论(0)
提交回复
热议问题