I understand there is a lot of documentation on editing crontabs via script, and I can do this by adding an entry with the following command:

line="* * * * * /my/folder/script.sh"
( crontab -l ; echo "$line" ) | crontab -

However, myself and a few others each have our own "sections" in our crontab under a superuser.

How can I insert this line under a keyword or string, such as underneath the line containing SPECIAL_JOB so as not to disturb others' sections and entries? I don't want to just keep appending new jobs at the bottom of the crontab.

The cron entry would look like this:

* * * * * /my/folder/script.sh

Ideally, I would delete the previous entry at this line to keep a single, fresh entry using this:

#remove entry
crontab -l | grep -ve '/my/folder/script.sh' | crontab -

This inserts after all # SPECIAL_JOB lines the $line string.

crontab -l | sed '/# SPECIAL_JOB/a'"$line" | crontab -
  • Works great -- quotes confused me until now. Thanks! – kstats9pt3 Feb 26 at 15:59
  • You could also consider using the sed c (change) command, to avoid the need for a separate step to delete the old entry e.g. sed -e '/^# SPECIAL_JOB/{n; c'"$line" -e '}' – steeldriver Feb 26 at 16:24

To avoid any issues with special characters in the replacement text, I would put the new cron entry into a file, named for example new-entry, then use:

{ crontab -l | sed '/^# SPECIAL_JOB/{
r /path/to/new-entry
}' } | crontab -

I made a minor change of subshell parenthesis ( ... ) to simple curly braces { ... }, because there's no real need to create a subshell; no harm, either!

I then use sed to parse the incoming text; it looks for a line that starts with # SPECIAL_JOB and then performs three actions:

  1. prints the current line then reads in the next line (this lets # SPECIAL_JOB be printed)
  2. r reads in the job from your file
  3. d then deletes the line that used to follow # SPECIAL_JOB -- the old job.

I would suggest using ansible un a larger scale.

  • I did not down-vote you, but think that you, as a new contributor, could benefit from a word of explanation: 1) ansible is not called for or expected here. You can acheive what OP requested without resorting to such extraneous pakage. 2) You did not address OP's specific query. 3) you did not provide reference and/or detailed instructions to back-up your answer. In other words you did not create or contribute value with your answer. We hope that you will continue to participate in the forum, adhering to its guidelines (unix.stackexchange.com/help) for Q/A. – Cbhihe Feb 27 at 13:38

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.