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
|Category||List of Unix and Linux commands|
|Firewall||CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04|
|Network Utilities||dig • host • ip • nmap|
|OpenVPN||CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04|
|Package Manager||apk • apt|
|Processes Management||bg • chroot • cron • disown • fg • jobs • killall • kill • pidof • pstree • pwdx • time|
|Searching||grep • whereis • which|
|User Information||groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w|
|WireGuard VPN||CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04|