thepip3r
thepip3r

Reputation: 2935

BASH - Compare string output from Date

I'm trying to use a timestamp to rotate log files each day. Store the last date-string and then for my infinite loop (currently sleeping every 5 mins) generate a new date and compare the two. If they are equal, it's the same day and writes to the same log file. If the values are different, writes to a new log file but before those new writes occur, tar the previous day up. My date-string eqaulity conditional isn't evaluating as I'd expect and I'm asking why this is:

lastdate=$(date +%Y%m%d)
while true
do
   curdate=$(date +%Y%m%d)

   echo "${lastdate}, ${curdate}"

   if [ "$lastdate" != "$curdate" ]; then
      ## do tar
      lastdate="$curdate"
   fi

   du >> "disk_du_${lastdate}.log"

   sleep 300
done

For the section in question, my echo statement shows both strings as having the same value but the conditional always runs even though I'm testing for inequality (or at least, that's the intent). I've tried different variations of the conditonal:

if [[ "$lastdate" != "$curdate" ]]; then
if [ $lastdate != $curdate ]; then
if [[ $lastdate != $curdate ]]; then
if [ "${lastdate}" != "${curdate}" ]; then

...but the conditional always runs even though the strings always show the same value. I based structuring the condtional off of: http://tldp.org/LDP/abs/html/comparison-ops.html, Example 7-5 so I'm hoping someone can tell me what I'm doing wrong. TIA.

Upvotes: 0

Views: 1512

Answers (1)

soft87
soft87

Reputation: 511

I advise you to have a check on your BASH

TEST:

GNU bash, version 4.3.11(1)-release (x86_64-pc-linux-gnu)

It's working:

#!/bin/bash
lastdate=$(date +%Y%m%d)
while true
do
   curdate=$(date +%Y%m%d)

   echo "${lastdate}, ${curdate}"

   if [ "$lastdate" != "$curdate" ]; then
      ## do tar
      lastdate="$curdate"
      echo "TRUE"
   else
      echo "FALSE"
   fi
   sleep 5
done

OUT:

20180404, 20180404
FALSE
20180404, 20180404
FALSE
20180404, 20180404
FALSE
20180404, 20180404
FALSE
20180404, 20180404
FALSE
20180404, 20180404
FALSE
20180404, 20180404
FALSE
20180404, 20180404
FALSE

Upvotes: 1

Related Questions