0

I am trying to compare dates in the while loop of a shell script. The shell script will be controlled by 2 conditions, like the following:

while [ $currentDate -le $currentDateMonthEnd -a $currentDate -le $toDate ]; do
...
done

The above is my current code, which complains of "integer expression expected". I have also tried using && and AND, which also do not work and complains of mismatching braces.

Could someone please provide the syntax to make the above comparison?

5
  • 6
    One of the variables is not set, or is not a number. You should test the code using something like set -x Commented Jun 10, 2013 at 14:38
  • 1
    If you are trying to compare full dates as it is, this will not work - as @Petesh notes, a date is not a number. You have to subtract your dates and check the delta/compare the individual days/months/years. Commented Jun 10, 2013 at 14:45
  • 3
    You might want to consider replacing shell scripting, in this application, with a real programming language that has date math functions; you'll probably find that it makes your life much easier to do so. Commented Jun 10, 2013 at 14:46
  • If you make your date format look like 20130610 for 2013-06-10 (10th June 2013), then you can compare numerically into date order. Pretty much any other date format is not as conventient. Commented Jun 10, 2013 at 17:03
  • @Pretesh, you were right. If you could put that as answer, I will accept. Commented Jun 10, 2013 at 18:18

2 Answers 2

1
dc ()
{
  [ $(date +%s -d "$1") $2 $(date +%s -d "$3") ]
}

while dc "$currentDate" -le "$currentDateMonthEnd" && dc "$currentDate" -le "$toDate"
do
  # ...
done
Sign up to request clarification or add additional context in comments.

Comments

0

following code works for me,

#! /bin/bash

toDate=`echo 2014/03/30 | tr -d "/"`
currentDate=`date +"%Y/%m/%d" | tr -d "/"`
currentDateMonthEnd=`date +%Y/%m/%d -d "-$(date +%d) days +1 month" | tr -d "/"` 

while [[ $currentDate -le $currentDateMonthEnd ]] && [[ $currentDate -le $toDate ]]   
do   
...  
done


#! /bin/sh 

while [ $currentDate -le $currentDateMonthEnd ] && [ $currentDate -le $toDate ] 
do   
...  
done

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.