1

I am looking for a programmatic way to append to crontab only if the entry does not exist. Also, the exit code must be 0 for both cases where the entry does not exist, or the entry exists.

I tried:

(crontab -l -u root 2>/dev/null | grep -F -v "@reboot /usr/bin/mycommand" || true; echo "@reboot /usr/bin/mycommand 2>&1") | sudo crontab -u root -

(crontab -l -u root 2>/dev/null | grep -F -v "@reboot /usr/bin/mycommand_2" || true; echo "@reboot /usr/bin/mycommand_2 2>&1") | sudo crontab -u root -

But the second still overrides everything in crontab.

0

untested, so beware

entries=( 
    "@reboot /usr/bin/mycommand"
    "@reboot /usr/bin/mycommand_2"
)
to_add=()
f=$(mktemp)

crontab -u root -l > "$f"
for entry in "${entries[@]}"; do
    grep -qF "$entry" "$f" || to_add+=( "$entry" )
done

{ cat "$f"; printf "%s\n" "${to_add[@]}"; } | crontab -u root "$f"
rm "$f"

Your solution only prints the new entry. Using tee with a process substutition will include the original crontab plus perhaps the new entry:

crontab -l -u root 2>/dev/null | tee >(sh -c '
    grep -qF "@reboot /usr/bin/mycommand" || echo "@reboot /usr/bin/mycommand 2>&1"
') | sudo crontab -u root -
| improve this answer | |
  • Thanks, I tried the one liner you provided, but it did not add it into crontab. – Justin May 24 at 23:15
  • If you take out the pipe to crontab, do you get the right content on stdout? – glenn jackman May 25 at 1:05

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.