0

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:

# SPECIAL_JOB
* * * * * /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 -
0

3 Answers 3

3

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

crontab -l | sed '/# SPECIAL_JOB/a'"$line" | crontab -
2
  • Works great -- quotes confused me until now. Thanks!
    – kstats9pt3
    Commented Feb 26, 2019 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 '}' Commented Feb 26, 2019 at 16:24
1

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/{
n
r /path/to/new-entry
d
}' } | 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.
-1

I would suggest using ansible un a larger scale.

1
  • 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
    Commented Feb 27, 2019 at 13:38

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.