1

Need some help in fixing simple bash script below. What it does is to compare dates in epoch format using if else. The script does not work as I intended because it always goes to the first condition DEPLOY all the time.

Even if I set the deploymentDate variable to be greater than currentDate it still goes to the first condition.

Can anyone suggest on how to fix it?

#!/bin/bash 
currentDate=$(date +s% ) 
deploymentDate=1513516201 

if [ "$currentDate" > "$deploymentDate" ] 
then 
    XSL="DEPLOY" 
else 
    XSL="DO NOT DEPLOY" 
fi 
echo $XSL 

Output

DEPLOY
Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
dimas
  • 1,151
  • 4
  • 22
  • 33

1 Answers1

2

wrong date usage.

  • date +%s with GNU date or compatible, or
  • awk 'BEGIN{srand(); printf "%lu\n", srand()}' with most awk implementations (will be guaranteed by the next version of the POSIX specification)

wrong statement usage:

  • if ((currentDate > deploymentDate)) (ksh/zsh/bash)
  • if [ "$currentDate" -gt "$deploymentDate" ] (POSIX)

Alternatively, you could use UTC dates in the YYYY-mm-dd HH:MM:SS format and use lexical comparison:

currentDate=$(date -u +'%Y-%m-%d %T') 
deploymentDate='2017-12-17 13:10:01' # UTC
if [[ "$currentDate" > "$deploymentDate" ]] # ksh/bash/zsh

if expr "$currentDate" '>' "$deploymentDate" > /dev/null # POSIX

Or numerical comparison with YYYYmmddHHMMSS date formats, but you could run into problems on systems or shells (like mksh) using 32bit integers for arithmetics.

Ipor Sircer
  • 14,546
  • 1
  • 27
  • 39