Skip to content
shellhacks.dev
Automation

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.

2 min read
Summarize in AI

An install script adds its cron job, and every time the script is run again the same job appears once more.

Shell
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 -r
Text
naive: 3 lines
guarded: 1 line
0 3 * * * /usr/local/bin/backup.sh

crontab -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.

Share

More snippets

Automation

Wait for a TCP Port to Open in a Bash Script

Wait until a TCP port accepts connections with a Bash loop that opens /dev/tcp/host/port, with no nc needed. It returns 0 once open, or 1 after the tries run out.

1 min read

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.