Adding a cronjob from a bash script

A quick tip this time about adding a cronjob from a bash script.

Every webproject I’m developing on has it’s own virtualhost in the Apache configuration and has a default project setup. Instead of configuring everything manually I’ve created a bash script which handles everything for me. Because I’m testing a lot (manually and automatically) on this project I wanted to flush the logs every week. As always there were some exceptions for projects for which I wanted to keep the logs a bit longer, so I decided to give every project it’s own cronjob entry for this. This enables me to disable the log flush for some projects.

So I wanted to add a cronjob from this bash script.

The vhost variable is already determined in this script, but you need to adjust the command to your needs anyway:

  1. As always, we need to set the shell first:
    #!/bin/bash
  2. Next we set the job as a string in a var:
    job="* * * * 0 rm /srv/httpdocs/vhost/$vhost/logs/*.log #flush vhost logs every sunday"
  3. At last we need to add this line to the crontab:
    (crontab -l; echo "$job" ) | crontab -

    To understand what this command does, I will split it up. The crontab -l command lists all the current jobs. Then we echo the contents of the var line and pipe the result of those to commands to the crontab.

The final script:

#!/bin/bash
job="* * * * 0 rm /srv/httpdocs/vhost/$vhost/logs/*.log #flush vhost logs every sunday"
(crontab -l; echo "$job" ) | crontab -

Now the new cronjob is installed!

Leave a Reply

Your email address will not be published. Required fields are marked *