I was recently wondering the same thing as I’m automating …

Thursday, 28th March 2024

Comment on How to add cron jobs from command line or bash scripts / Add crontab jobs in a script by John.

I was recently wondering the same thing as I’m automating a bunch of systems and need to add quite a few cronjobs and did not want to overwrite anything they currently had. So I found this page. The method I used however was this (using your example cronjob):

crontab -l|sed ‘$a*/5 * * * * /root/myscript.sh’|crontab –

In this way, you obtain the previous values using crontab -l and append */5 * * * * /root/myscript.sh to the entries using sed and then pipe the entirety back into crontab in one fell swoop without having to mess with temporary files.

The best part, is this can be modified easily to alter cronjobs for different users (if you have permission) using the -u flag for crontab. Like so:

crontab -u john -l|sed ‘$a*/5 * * * * /root/myscript.sh’|crontab -u john –

Share this on:

Comments are closed.