Scripts – How to Add a Cronjob Using a Script


I wrote this script, but it doesn't work:

#! /bin/bash
cront=$(crontab -e)
echo 00 23 * * 5 tar -cpzf /var/backup.tar.gz /home/$USER >> $cront

How can I add a cronjob using a script?

Best Answer

This should do the job:

crontab -l|sed "\$a0 23 * * 5 tar -cpzf /var/backup.tar.gz /home/$USER"|crontab -

This chain of commands adds everything after \$a in the sed expression (bold) as a new line to the current user's crontab. crontab -l prints the current crontab, sed adds the line to the end and crontab - takes the stdin from the pipe and makes it the new crontab. Note that this works only if you're not messing with different users, if you plan to do that read about the -u option in man crontab first.

Related Question