Jarno
Jarno

Reputation: 51

Bash: start date less than equal to end date

#!/bin/bash
# slightly malformed input data
input_start=2014-11-1
input_end=2016-01-1

# After this, startdate and enddate will be valid ISO 8601 dates,
# or the script will have aborted when it encountered unparseable data
# such as input_end=abcd
startdate=$(date -I -d "$input_start") || exit -1
enddate=$(date -I -d "$input_end")     || exit -1

m="$startdate"
while [ "$m" != "$enddate" ]; do
  echo $m 
  m=$(date -I -d "$m + 1 month")
done

"Script is running fine but when I want to change the While loop condition i.e '<=' 'less then or equal to' its giving error even I tried using "-le".What I want to do here is startdate <= enddate in while loop. Can anyone suggest what needs to done to overcome this issue.

Same Code

Upvotes: 5

Views: 4699

Answers (2)

hroptatyr
hroptatyr

Reputation: 4809

With dateutils' datetest this is simple:

$ datetest 2014-11-1 --le 2016-01-1 ; echo $?
0

$ datetest 2014-11-1 --gt 2016-01-1 ; echo $?
1

Then again, what you want is simply done by dateseq, which also happens to be a tool of the dateutils suite.

$ dateseq 2014-11-1 +1mo 2016-01-1
2014-11-01
2014-12-01
2015-01-01
2015-02-01
2015-03-01
2015-04-01
2015-05-01
2015-06-01
2015-07-01
2015-08-01
2015-09-01
2015-10-01
2015-11-01
2015-12-01
2016-01-01

Disclaimer: I am the author of the package.

Upvotes: 4

anishsane
anishsane

Reputation: 20980

-le is for numeric data. 2014-11-01 is not a number. Use < or >. (You need to escape them as \< or \>. Or use [[ instead of [.)

effectively, change

while [ "$m" != "$enddate" ]; do

to

until [ "$m" \> "$enddate" ]; do

or

until [ "$m" '>' "$enddate" ]; do

or

until [[ "$m" > "$enddate" ]]; do

Alternately, use seconds since epoch instead of ISO8601 format.

while [ "$(date -d "$m" +%s)" -le  "$(date -d "$enddate" +%s)" ]; do

Upvotes: 6

Related Questions