0

I'm trying to compare two dates. The system date vs a file date. I'm having trouble and the error I am getting is this:

./hello.sh: line 25: [10-18-2018: command not found

I have also tried with =,==,-eq.

#Setting variable
now=$(date +"%m-%d-%Y")
#Testing variable        
echo "Current System Date: $now"
#Setting variable        
filedate=$(date -r hello.sh "+%m-%d-%Y")
#Testing variable        
echo "hello.sh date: $filedate"

if [$now -ge  $filedate]
then
echo This statement works
else
echo This statement didnt work
fi
NeoAer
  • 327
  • 3
  • 15
  • 2
    syntax errors can (usually) be debugged by pasting your code at https://shellcheck.net. You'll need to include a valid "she-bang" line as the first line, usually `#!/bin/bash` will suffice. Good luck. – shellter Oct 18 '18 at 16:35

1 Answers1

2

Just a couple simple syntax modifications:

#!/bin/bash

#Setting variable
now=$(date +"%m-%d-%Y")
#Testing variable
echo "Current System Date: $now"
#Setting variable
filedate=$(date -r hello.sh "+%m-%d-%Y")
#Testing variable
echo "hello.sh date: $filedate"

if [[ $now ==  $filedate ]]
then
    echo "This statement works"
else
    echo "This statement didnt work"
fi
  • in the if, you must put spaces after [ and before ]
  • you are comparing text, so -ge does not work. the "-" comparisons work for numbers. Here you want to use == to compare text.
  • Reflex for me, I put " around echo text.

This will work for cases where the dates are the same. If you need "greater than" or "smaller than", put the dates in timestamp format (+%s) and compare the numbers. Then you could use the -ge or others of the same type.

Nic3500
  • 8,144
  • 10
  • 29
  • 40
  • shellcheck.net is a great tool to verify your syntax. Then there is this page: https://mywiki.wooledge.org/BashGuide with a LOT of information. It is a bit "dry", you could research some basic tutorials / reference on the web. – Nic3500 Oct 18 '18 at 16:49