I'm new to Bash, apologies in advance.
Set-up
I have a particular end date end which depends on a particular starting date s and a period length p such that, end=s+p.
Problem
I want to execute a command if and only if today's date is before or equal to the end date.
That is: execute command iff date ≤ end.
Code
s='20/09/2017'
p='1'
end=$( date -j -v +"$p"d -f "%d/%m/%Y" "$s")
if [[ date < “$end” ]];
then
echo 'ok'
fi
There are 2 things not the way they should be,
p=1 implies end = '21/09/2017' < date = '26/09/2017', but still I get an ok.date < “$end” but I want date ≤ “$end”How to correct 1 and 2?
When you format the date like YYYYMMDD you can simply use an alphanumeric comparison:
start=$(date +'%Y%m%d')
end=$(date +'%Y%m%d')
# -gt means greater than - for example.
# check `help test` to get all available operators
if [ $start -gt $end ] ; then ...
First you need to use a date format which is lexicographical, meaning the big units come first. I highly recommend the ISO standard YYYY-MM-DD or YYYYMMDD. Second, <= can be written as -le (less or equal).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With