bash : Automate add/modify/delete of cron jobs from a script

If you have auto installing packages there could be times when a cron job needs to be added. So the script has to be able to create new cron entries or delete old ones. One solution is to create temporary files in between to hold the other unaffected cron entries that are currently installed, add the new entry and then install this file using crontab. Creating of temporary files should be avoided in between as there are risks. So here is an elegant solution which uses piping in the output of multiple commands.

To remove already existing cron job (rdate for user unixite in example below) use a syntax like

crontab -l -u unixite | grep -v rdate | crontab -u unixite -

This pipe chain lists the existing crontab entries, removes any containing the string rdate, then reloads the resulting data by piping it back to crontab of user unixite. “-” is for reading from the stream or terminal (see Note below). No useless temporary file, no security risk.

To add new crontab entries use a subshell as below.

(
crontab -l -u unixite
cat >>'EOF'
@daily /opt/scripts/cleanup.sh
### Here you can add as many crontab commands as you want
EOF
) | crontab -u unixite -

This takes in account the current cronjobs by using crontab -l, then combines its output with the new cron job that should be added. All this output is reloaded back using the last crontab.

Interoperability Issues between SunOS and Linux

Now few words of caution on interoperability issues across SunOS and Linux.

  1. crontab on SunOS does not require “-u” flag for the user. So instead of crontab -l -u unixite (which would list all cron jobs for user unixite on Linux), it will become crontab -l unixite.
  2. crontab on SunOS does not require “-” to read from terminal or stream. So on SunOS our original removal command becomes crontab -l unixite | grep -v rdate | crontab unixite.