11

I want to write a script that add a cron job to my crontab but without user intervention like editing a file using crontab -e. Is there a way to programatically manipulate the cron jobs from command line? Any suggestion on how to do that? Thanks in advance.

1
  • 1
    crontab uses the values of the VISUAL and EDITOR variables to determine the program which will edit the crontab - the variables can contain, for example, the path to a script, or shell commands, using which you can programmatically edit it. See for example, unix.stackexchange.com/a/179445/70524 using this to edit suoders.
    – muru
    Feb 25, 2015 at 14:12

2 Answers 2

18

To install a crontab:

echo "1 1  * * *  test" | crontab -

should do the trick.

NOTICE that this substitutes the whole crontab. You have to save the value it had with crontab -l if you just want to add/edit things. For example

(crontab -l && echo "1 1  * * *  test") | crontab -

will add the line to your crontab.

1
  • 1
    "crontab -l" produces on some linux distros a warning message if you have no crontabs. So this will concatenate the warning as a cronjob. Use "crontab -l 2>/dev/null" instead.
    – Niels
    Dec 8, 2020 at 7:50
0

How about the following:

crontab -l | some-editing-command | EDITOR=cat crontab -e

The first part of the pipe lists the current crontab, the second part is supposed to modify it in a sensible way, and the third part reinstalls it using cat as the "editor", as suggested by @muru.

1
  • You do not need to redefine EDITOR. Just do: crontab -l | some-editing-command | crontab - Feb 7, 2023 at 11:06

Not the answer you're looking for? Browse other questions tagged .