How can I get this week’s Monday in a Bash script?

0
7
Asked By CuriousCoder42 On

I'm writing a Bash script and need to retrieve the date of this week's Monday. I initially tried using the command `date -d "last Monday" +"%d %b"`, but I noticed that it gives the date from the previous week when it is currently Monday, instead of today's date. Do I need to tweak my command, or would it be better to implement an if statement to check if today is Monday? If it is, I want it to show this Monday; otherwise, it should show the last Monday. Hope that makes sense! Thanks for any help!

3 Answers

Answered By TechieTina23 On

While your command works well for showing the last Monday when it isn't Monday, a straightforward way to handle your request is to use this combined command: `date -d "$(test $(date +%u) -eq 1 && echo "today" || echo "last Monday")" +"%d %b"`. This checks if today is Monday and adjusts accordingly.

Answered By ScriptGuru99 On

It seems like you might be confusing the command a bit. If you want the date of this Monday when today is Monday, you could use `date -d "this Monday" +"%d %b"`. If today is any other day, the command will still give you the current week’s Monday. Giving that a shot should solve your issue!

Answered By BashBrawler88 On

You might want to try using just `date -d "this Monday" +"%d %b"` instead. It's clearer and avoids the confusion of the `last Monday` argument when today is already Monday.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.