I'm working on developing a cron script for running a nightly database procedure, and I'm trying to understand how to evolve it from a simple one-liner into something more robust. I've learned about logging with 'exec', using 'trap' for cleanup, setting 'set -euo pipefail', implementing lockfiles, and adding alerts. The goal is to understand the common pitfalls when running scripts under cron and to harden the script step-by-step. I'd love any tips or best practices that could help make my script more reliable and efficient!
5 Answers
Don't forget to add an alert system for your script! Notifications can be critical for catching failures. Cron sends output to whatever is set in ${LOGNAME} or ${MAILTO}, so leverage those to get notifications when something goes wrong.
When writing scripts for novices, make sure to use long options in your commands. It’s much easier for beginners to read commands like `mysql --database=mydb --execute='CALL nightly_job();' --password='secret' --username=app_user` rather than their shortened forms. Also, consider listing options vertically for better readability.
Adding proper error handling with `set -euo pipefail` can help catch errors early, but it's worth noting that there's some debate around using 'euo' settings. I usually set them up and comment out 'pipefail' when necessary, explaining why for future users of my script just in case.
When setting up your cron jobs, always remember to define your PATH. It’s generally a bad idea to use absolute paths everywhere because those paths might change. Setting a clean path explicitly is often a better strategy—start with minimal settings and add only the necessary directories to avoid issues.
A common mistake people make is to overlook syslog for logging. Instead of creating a basic logging system, you can enhance your cron job by redirecting output to syslog using `... | logger -t jobname`. This not only timestamps your logs but also keeps everything organized according to your system's log settings, plus it comes with the benefits of log rotation and easier exporting to log collectors.

Related Questions
How To Get Your Domain Unblocked From Facebook
How To Find A String In a Directory of Files Using Linux