4

I trying to print date between 2 dates using while loop in a bash script.

But when i execute i am getting below error:

test.sh: line 8: [: 02-12-14: integer expression expected

Below is my code, can anyone help me out

#!/bin/bash

sdate=02-12-14
edate=02-25-14


while [ "$sdate" -le "$edate" ]
do
echo $sdate
sdate=$(date +%m-%d-%y -d "$sdate + 1 day")
done
Jayesh Bhoi
  • 24,694
  • 15
  • 58
  • 73
user3796869
  • 231
  • 4
  • 11
  • You should probably compute the difference. Like here - http://stackoverflow.com/questions/8116503/how-to-compare-two-datetime-strings-and-return-difference-in-hours-bash-shell – Engineer2021 Jul 21 '14 at 10:44
  • 1
    use the `epoch seconds` for the compare, or format your date as YYYYMMDD. (both are integer). – clt60 Jul 21 '14 at 10:45
  • 1
    You are using an arithmetic operator to compare strings –  Jul 21 '14 at 10:45
  • You can not direct compare that. It's string. So you need to manipulate it by date data tyep like `sdate=$(date -d 12-02-14 +"%y%m%d")` and `edate=$(date -d 25-02-14 +"%y%m%d")`. – Jayesh Bhoi Jul 21 '14 at 10:53
  • while you can compare strings with [[ "02-12-14" > "01-25-14" ]], the result will not be what you may expect, with your date format. If it was YY-MM-DD, that string comparison could be used. Otherwise, 01-* will be less than 02-*, regardless of year. – Deleted User Jul 21 '14 at 10:55

1 Answers1

4

You should store them as timestamps:

#!/bin/bash

sdate=$(date -d '2014-02-12' +%s)
edate=$(date -d '2014-02-25' +%s)

while [[ sdate -le edate ]]; do
    date -d "@$sdate" '+%m-%d-%y'
    sdate=$(date -d "$(date -d "@${sdate}" ) + 1 day" +%s)
done

Output:

02-12-14
02-13-14
02-14-14
02-15-14
02-16-14
02-17-14
02-18-14
02-19-14
02-20-14
02-21-14
02-22-14
02-23-14
02-24-14
02-25-14
  • Always prefer [[ ]] over [ ] when it comes to conditional expressions in Bash. (( )) may also be a preference.

  • It requires GNU date. e.g. date --version = date (GNU coreutils) 8.21 ...

  • mm-dd-yy is not a format acceptable by date for input so I used yyyy-mm-dd which is acceptable.

konsolebox
  • 72,135
  • 12
  • 99
  • 105