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.
An uninstall script has to delete one line from the crontab and leave the rest as it was.
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*/5 * * * * /usr/local/bin/ping.sh
# backup.sh runs nightly
---
*/5 * * * * /usr/local/bin/ping.shThe 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.