This is a classic problem. One of our FAQ is about cron job. I received lots of email with a question:
How do I run my script on 3rd Monday or 4th Friday only?
Cron does not offer this kind of facility i.e. you cannot run a script on the Nth weekday of the month.
However with one shell liner you can force to run a script on a given day:
Consider following date command, it will print day:
$ date +%a
You can compare output with weekday name using bash test [exrp ] syntax and the control operators && (AND list), you can write:
$ [ $(date '+%a') == 'Thu' ] && echo 'Today is Thu, run a command' || echo 'Noop'
First echo command get exectued only on Thursday. Now all you have to do is write a cron job to execute on first Monday:
# crontab -e
Now append code as follows:
# Run a script called myscript.sh on First Monday at 11:30:
30 11 1-7 * Mon [ "$(date '+%a')" == "Mon" ] && /path/to/myscript.sh
Hope this small tip will save your day. Please do share some of your favorite bash / shell scripting hacks in the comments. I will highlight some of the best in next shell scripting post.
- Executing script or command on the last day of a month
- Linux / UNIX cron job quick start guide
- Just like a seasoned admin, read bash and date man pages
- 30 Handy Bash Shell Aliases For Linux / Unix / Mac OS X
- Top 30 Nmap Command Examples For Sys/Network Admins
- 25 PHP Security Best Practices For Sys Admins
- 20 Linux System Monitoring Tools Every SysAdmin Should Know
- 20 Linux Server Hardening Security Tips
- Linux: 20 Iptables Examples For New SysAdmins
- Top 20 OpenSSH Server Best Security Practices
- Top 20 Nginx WebServer Best Security Practices
- 20 Examples: Make Sure Unix / Linux Configuration Files Are Free From Syntax Errors
- 15 Greatest Open Source Terminal Applications Of 2012
- My 10 UNIX Command Line Mistakes
- Top 10 Open Source Web-Based Project Management Software
- Top 5 Email Client For Linux, Mac OS X, and Windows Users
- The Novice Guide To Buying A Linux Laptop