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.

Justin
  • 5,328
  • 19
  • 64
  • 84

1 Answers1

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 -
glenn jackman
  • 4,630
  • 1
  • 17
  • 20