1

I'm trying to make a script that is working from 12/24/2020 through 06/01/2021. For now I olny have it working only for 2 dates with this:

if [ "$(date +'%m%d')" != "1224" ] && [ "$(date +'%m%d')" != "1226" ]; 

So this script should be working from 12/24 - 01/06. Any suggestions? Thanks

3
  • 3
    If you have your date command output year, month, day, i.e., 20201224, then you can just use normal string compare for a range check. Commented Dec 26, 2020 at 1:57
  • A complication occurs to me: do you want the test to be applied in the local time zone, or GMT, or something else? Commented Dec 26, 2020 at 6:18
  • To my local time zone, yes. I'm in Italy. Commented Dec 26, 2020 at 9:58

2 Answers 2

3

You can use the +%s option in date to convert the start/finish dates to epoch time. You supply the dates using the -d option.

Then, you retrieve the current date using +%s again and compare using standard integer comparison, like this:

start=$(date +%s -d '12/24/2020') finish=$(date +%s -d '06/02/2021') now=$(date +%s) if [ $now -ge $start ] && [ $now -lt $finish ] then echo "Do something" else echo "Skip" fi 

Edit: For the finish date, its necessary to use the day after your intended finishing date and compare using -lt. This is because date will return the timestamp for the start of the specified date. So doing this, you end up having the comparison succeed until midnight on 06/01/2021. Thanks to @gordon-davisson for pointing this out.

Sign up to request clarification or add additional context in comments.

5 Comments

Small problem: date +%s -d '06/01/2021' gets the time midnight at the beginning of 06/01/2021. If you want it to work through 6/1/2021 (i.e. until the midnight at the end of 6/1/2021, you should use date +%s -d '06/02/2021' and a -lt test.
&& and multiple tests is preferred over using the deprecated -a, see for example BashFAQ/031.
That's really unfortunate. I never knew that about test (or maybe I did and forgot over time..), and yet it was in the man page all this time: NOTE: Binary -a and -o are inherently ambiguous. Use 'test EXPR1 && test EXPR2' or 'test EXPR1 || test EXPR2' instead.
Is 06/01/2021 January 6 or June 1? I would suggest specifying the dates in ISO format, which date understands, and not use the ambiguous US format. So 2021-06-01 for June 1.
I was just using the original dates verbatim from the question.. But based on that I think the intention was for June 1, which you can tell from the start date 12/24.
1
beg='20201224' end='20210601' now=$(date +'%Y%m%d') if (( beg <= now )) && (( now <= end)); then 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.