0

I have a bash script that is comparing 2 dates ( one from a file that is stored in the server and the other using date command), it was working just fine but after the month ended it cannot compare the 2 dates, here is the code:

consult)

                    local FECHA=`curl -s $URL_UPDATE | jq '.result[0].message.text' | awk -F "_" '{print $2}' | tr -d '"'`

                    local DATE=`date "+%d-%m-%y"`

                    if [[ ${FECHA#0} -ge ${DATE#0} ]]; then

                            $SEND"Wrong Date"

                    else

                           $SEND"Right Date"
                 
                    fi

PD: The URL_UPDATE variable is just the Telegram API getUpdates url, I take the first date from the user via Telegram after the _ if the user puts any. About $SEND, is the "send_message" function from the Telegram API.

  • Lexical comparison of dates in dd-mm-yy format will of course not work like you hope. This is why we use yyyy-mm-dd format (or seconds since the epoch) for anything which needs to be machine-readable. – tripleee Jul 01 '21 at 19:17
  • @tripleee I was using that format because the file where i am taking the first date from is in that format, i will try with the seconds since epoch, Thanks. – Andres Gamez Jul 01 '21 at 19:28

1 Answers1

1

[ -ge ] compares numbers. But dates of the format dd-mm-yyyy are not numbers.

If you use the date format yyyymmdd you can compare dates using -ge. You can convert the first date using sed, which can also do the things you did with awk and tr.

local fecha=$(curl -s "$URL_UPDATE" | jq '.result[0].message.text' |
              sed -En 's/^[^_]*_[^_]*(..)-(..)-(....).*/\3\2\1/p')
local date=$(date +%y%m%d)
if (( fecha >= date )); then
  # do stuff
else
  # do stuff
fi

By the way:

  • Variables in bash should be written in lowercase and not in ALLCAPS, to avoid accidental collision with special environment variables.
  • $(cmd) is better than `cmd` as it can be nested.
  • (( var >= var )) is easier to write/read than [[ "$var" -ge "$var" ]].
  • In your code $SEND"Wrong Date" there is probably a space missing between $SEND and "Wrong date". Also, instead of storing a command inside the variable $SEND, define a function send() { ... }.
Socowi
  • 25,550
  • 3
  • 32
  • 54