2

I am trying to create a script in which 4 days ago date should be equal to to current date if it is not then add 1 more day and check. Below is the one i have created but still not clear about answer.


#!/bin/bash

batchdate=`date --date "4 day ago" '+%Y%m%d'`
matchdate=`date --date "today" '+%Y%m%d'`

for i in {0..4}
do
    if [ $batchdate != $matchdate && $NEXT_DATE != $matchdate ]; then

   NEXT_DATE=$(date +%Y%m%d -d "$batchdate + $i day")

   echo "$NEXT_DATE"

   break

   fi

done
blackpen
  • 2,339
  • 13
  • 15
Amit Alone
  • 21
  • 3
  • 2
    `batchdate` and `matchdate` will *never* be equal; they are initialized to two distinct dates, and you never change the value of either variable. – chepner Sep 10 '16 at 13:50
  • but maybe you mean to OR the two date tests, i.e. `||` instead of `&&`. Good luck. – shellter Sep 10 '16 at 13:52
  • 1
    Also, you are using two different formats for `matchdate` and `batchdate`/`NEXT_DATE`, further ensuring that the strings will never be equal. `bash` doesn't do date comparison, only string comparison. – chepner Sep 10 '16 at 13:52

1 Answers1

5

First, define a little helper function to avoid doing the same thing in slightly different ways:

get_date () {
    date +%Y-%m-%d --date "$1"
}

Now, you have two variables: the current date, which will never change, and the starting date, which you will increment one day at a time until it matches the current date.

then=$(get_date "4 days ago")
now=$(get_date "today")

while [[ $then != $now ]]; do
  then=$(get_date "$then + 1 day")
  echo "$then"
done
chepner
  • 497,756
  • 71
  • 530
  • 681