13

I'm writing a a Horoscope RSS script as an intro to Unix/Linux project, and ran into an issue my Professor couldn't fix in the time I was able to stay after class. Since I couldn't figure out how to use actual dates as what to check, I thought I'd try basic arithmetic by having user input be standard numbers in MMDD format. According to him, the script seems to be reading input as octal code instead of integer. Here's a sample of the script:

    elif [ "$olddate" -gt 1121 ] && [ "$olddate" -lt 1131 ] || [ "$olddate" -gt 1200 ] && [ "$olddate" -lt 1222 ]
then
echo "You are Sagittarius"
exit
elif [ "$olddate" -gt 1221 ] && [ "$olddate" -lt 1232 ] || [ "$olddate" -gt 0100 ] && [ "$olddate" -lt 0120 ]
then
echo "You are Capricorn"
exit

This is the bare bones, I took out the RSS part. "olddate" is the expected input from my read prompt. While 1121 to 1131, 1200 to 1222, and 0100 to 0120 work, nothing between 1221 to 1232 does. He figured that was the problem since putting 113 without a leading 0 worked for Capricorn. I also just ran into a problem where 0323 which was supposed to give me Aries (-gt 0320 && -lt 0332) gave me Aquarius (whose dates are -gt 0119 && -lt 0132 || -gt 0200 && -lt 0219) as well as 0417 not working (which is the other date range for Aries, -gt 0400 && -lt 0420).

What do I do so that BASH interprets input as the actual numbers? He tried changing the read prompt to expect "userdate" as input and then adding

olddate=`printf '%d\n' "$userdate"`

but that did not work. Thanks in advance to anyone who can help me out on this!

  • Can't duplicate on bash 4.4.12. – Ignacio Vazquez-Abrams Nov 23 '17 at 1:35
  • 1
    $olddate is a string, not a number, so use string comparisons and avoid the whole mess. – Stephen Harris Nov 23 '17 at 1:51
  • 2
    @StephenHarris: So are the values to the right of the operators. That's why test has explicit numeric operators. – Ignacio Vazquez-Abrams Nov 23 '17 at 1:56
  • One thing to note, but unrelated to the core question, is that your zodiac sign is also partially dependent on the year you were born in, if your day and month of birth was close to the transition between 2 zodiac signs. Your zodiac sign is based on the 1/12th part of the sky the sun was in at the time you were born, but because the number of days in a year isn't a whole number nor divisible by 12, there is some variation from year to year. This variation is too complex to really capture in if-else trees, but it's just something which might be good to know. – Nzall Nov 23 '17 at 13:35
26

You can force conversion of a number to a specific base in bash like so:

$ foo=400
$ echo $((8#$foo))
256
$ bar=0100
$ echo $((10#$bar))
100

In general the format is $((base#value)).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.