Print incremental date using while loop in bash

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

But when I execute, I get below the error:

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

Below is my code, can anyone help me.

#!/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
+4
source share
1 answer

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

Conclusion:

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 preferred.

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

  • mm-dd-yyis not a format acceptable for dateinput, so I used yyyy-mm-ddone that is acceptable.

+3
source

All Articles