0

Is it possible to print to crontab with an heredocument?

I tried these but failed:

cat <<-"CRONTAB" > crontab
    0 0 * * * cat /dev/null > /var/mail/root
    0 1 * * 0 certbot renew -q
CRONTAB

and:

bash <<-"CRONTAB" > crontab
    0 0 * * * cat /dev/null > /var/mail/root
    0 1 * * 0 certbot renew -q
CRONTAB

This on the other hand is not an heredocument, but worked:

# CRONTAB
echo "
    0 0 * * * cat /dev/null > /var/mail/root
    0 1 * * 0 certbot renew -q
" | crontab

I thus wonder if it's even possible with heredocument.

  • 2
    > crontab is a file redirection - not the same as | crontab – steeldriver Jan 12 '18 at 5:05
  • 2
    You could just define the job in a new file in /etc/cron.d. Might be simpler. – Wildcard Jan 12 '18 at 5:15
  • @steeldriver how do you define | crontab? – Arcticooling Jan 12 '18 at 6:04
  • I think @steeldriver is pointing out that crontab is a command. On some distros the crontab file may also be named "crontab," but at least on RHEL it is not. (It's called /var/spool/cron/$USER.) – Wildcard Jan 12 '18 at 6:13
  • @Wildcard yes sorry if I wasn't very clear - I meant that the OP's first two snippets create a (likely local) file named crontab whereas the third pipes the content to the crontab command. – steeldriver Jan 12 '18 at 13:21
6

As others have pointed out, crontab is a command, so all you need to do is feed it the heredoc:

crontab <<-"CRONTAB"

But as has been mentioned before, it’s an awful lot easier to manage cron jobs by manipulating files in /etc/cron.daily, /etc/cron.d etc.

  • 4
    Especially if you don't want to clobber any cronjobs that may have already been defined! – Wildcard Jan 12 '18 at 6:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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