Skip to content
shellhacks.dev
Automation

Remove One Cron Job from a Crontab in a Shell Script

Remove one job from the crontab in a script with crontab -l piped through grep -vF and back into crontab -. Match the full command, not just a file name.

1 min read
Summarize in AI

An uninstall script has to delete one line from the crontab and leave the rest as it was.

Shell
table=$(printf '%s\n' '0 3 * * * /usr/local/bin/backup.sh' '*/5 * * * * /usr/local/bin/ping.sh' '# backup.sh runs nightly')
echo "$table" | crontab -
crontab -l | grep -vF '/usr/local/bin/backup.sh' | crontab -
crontab -l
echo ---
echo "$table" | crontab -
crontab -l | grep -vF 'backup.sh' | crontab -
crontab -l
crontab -r
Text
*/5 * * * * /usr/local/bin/ping.sh
# backup.sh runs nightly
---
*/5 * * * * /usr/local/bin/ping.sh

The pipeline reads the table, drops every line that holds the fixed string with grep -vF, and installs what is left. The first run matches the full path, so the comment that only says backup.sh survives. The second run matches the short name and takes the comment along with the job. -F keeps dots and stars literal. See crontab(1) for -l and the standard input form.

When grep -v finds nothing to keep it exits 1, and the empty input then installs an empty table, which removes every job, so check the result before relying on a status. If crontab -l fails because the user has no crontab, the same pipeline installs an empty one. Work on a saved copy, crontab -l > cron.bak, so there is something to restore.

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.