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?

  • You should quote what you want to echo, try echo * and echo "*" in a non-empty directory to see why. – dessert Nov 30 '17 at 18:06
  • 1
    If you're on a recent version of Ubuntu, consider programmatically adding systemd timers instead of working with cron programmatically. When I'm making a new script, I find it easer to make a timer file, then adding it programmatically via the install script. Note, though, that user-level systemd timers have trouble on RedHat/CentOS and the entire system is underdocumented and might be needlessly complicated for your case – Ben Nov 30 '17 at 19:32

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.

| improve this answer | |

Not the answer you're looking for? Browse other questions tagged or ask your own question.