Add a Cron Job from a Script Without Duplicates
Add a job to the crontab from a script without duplicating it. Test for the exact line with grep -qxF first, or each run of the script adds another copy.
An install script adds its cron job, and every time the script is run again the same job appears once more.
job='0 3 * * * /usr/local/bin/backup.sh'
for i in 1 2 3; do (crontab -l 2>/dev/null; echo "$job") | crontab -; done
echo "naive: $(crontab -l | wc -l) lines"
crontab -r
add_job() { crontab -l 2>/dev/null | grep -qxF "$job" || { crontab -l 2>/dev/null; echo "$job"; } | crontab -; }
add_job; add_job; add_job
echo "guarded: $(crontab -l | wc -l) line"
crontab -l
crontab -rnaive: 3 lines
guarded: 1 line
0 3 * * * /usr/local/bin/backup.shcrontab -l prints the current table and crontab - replaces it with standard input, so the usual append is a read, an echo and a write back. Nothing in that checks for an existing line. grep -q asks only whether the line is there, -x requires the whole line to match, and -F takes the job literally, which matters because the schedule is full of stars that a regular expression would read as repetition. The options are in the GNU grep manual.
The check is for an identical line, so a job whose schedule you changed is added as a second job; remove the old one first or tag the line with a comment you can search for. crontab -l exits 1 when the user has no crontab, hence the redirect, which matters under set -e. Two copies of the script running at once can still race on the read and the write.