Skip to main content
Bash Scripting – Complete Beginner to Advanced Guide
CHAPTER 13 Intermediate

Scheduling Tasks with Cron

Updated: May 16, 2026
25 min read

# CHAPTER 13

Scheduling Tasks with Cron

1. Introduction

A meticulously crafted log-cleaning script is entirely useless if the systems administrator forgets to run it on Friday evening. The ultimate objective of DevOps scripting is the complete removal of the human element. In Unix, the supreme orchestrator of time is a permanent background daemon called cron. It runs silently 24 hours a day, checking a master schedule every 60 seconds. If a task is scheduled for that exact minute, cron executes your shell script flawlessly without human intervention. In this chapter, we will master the cryptic 5-field syntax of the crontab file, schedule scripts to run daily, weekly, or upon server reboot, and conquer the unique environmental constraints of scripts executed by the cron daemon.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Access and edit the user-specific cron schedule using crontab -e.
  • Decipher and author the 5-field cron time syntax (Minute, Hour, Day, Month, DayOfWeek).
  • Schedule a shell script to execute at specific, recurring periodic intervals.
  • Route standard output and standard error from a cron job into a permanent log file.
  • Understand and mitigate the restricted $PATH limitations inherent to the cron environment.

3. The crontab File

Every user on a Unix system possesses their own personal scheduling file, known as a crontab (Cron Table). To edit your schedule, you execute:
sh
1
crontab -e

*(Note: If prompted, press 1 to select the nano text editor).* To simply view your schedule without risking accidental edits, type crontab -l (list).

4. Cron Syntax (The 5 Stars)

A cron job entry consists of 5 asterisks (*) followed by the absolute pathway to the script you wish to execute. The five fields represent: [Minute] [Hour] [DayofMonth] [Month] [DayofWeek]
  • An asterisk * signifies "Every".
  • Hours are calculated in 24-hour military time (0 = Midnight, 23 = 11 PM).
  • Day of Week ranges from 0-7 (where both 0 and 7 represent Sunday).

Standard Examples:

sh
12345678
# Run a script every day at exactly 2:30 AM
30 2 * * * /home/admin/backup.sh

# Run a script at 5:00 PM every Friday (Day 5)
0 17 * * 5 /home/admin/weekly_report.sh

# Run a script EVERY minute of EVERY day (Dangerous, but useful for monitoring)
* * * * * /home/admin/monitor.sh

Advanced Syntax Modifiers:

  • Step Values (/): Run a script every 15 minutes: */15 * * * *
  • Multiple Values (,): Run at 1:00 AM and 1:00 PM: 0 1,13 * * *
  • Upon Reboot (@reboot): Run a script exactly once when the server boots up: @reboot /home/admin/startup.sh

5. Managing Cron Output (Logging)

If you run ./backup.sh manually, the text Backup Successful prints to your screen. When cron executes ./backup.sh at 3:00 AM, you are asleep. There is no screen. If you do not explicitly redirect the output using the tools learned in Chapter 9, cron will attempt to email the output to a local mailbox (which is usually unconfigured) and the data vanishes forever.

You must redirect cron output into a dedicated log file!

sh
12
# Append stdout AND stderr to a persistent log file using >> and 2>&1
0 2 * * * /home/admin/backup.sh >> /var/log/cron_backup.log 2>&1

6. The Cron Environment Trap

This is the #1 reason why a shell script works perfectly for a human, but fails catastrophically when executed by cron. When you log in, your profile loads your customized $PATH variables (allowing you to simply type commands like tar or docker). When cron wakes up, it operates in a stripped-down, bare-bones environment. It does not load your profile. If your script uses a custom tool, cron will not be able to locate it, and the script will silently crash.

The Fix: Inside your shell script, ALWAYS utilize absolute paths for critical commands or files.

  • *Bad Practice:* tar -czvf backup.tar /data
  • *Professional Practice:* /usr/bin/tar -czvf /tmp/backup.tar /data

7. Diagrams/Visual Suggestions

*Visual Concept: The Cron Time Map* Create a visual translation of the string 30 14 * * 1. Draw five sequential boxes.
  • Box 1: 30 (Label below: Minute, 0-59).
  • Box 2: 14 (Label below: Hour, 0-23).
  • Box 3: * (Label below: Day of Month, 1-31).
  • Box 4: * (Label below: Month, 1-12).
  • Box 5: 1 (Label below: Day of Week, 0-7, Sun-Sun).
Show the final translation in a large bold font: "Run at 2:30 PM, every Monday." This visual mapping is universally required for beginners to parse the syntax.

8. Best Practices

  • Use crontab.guru: Do not attempt to guess complex cron syntax in your head. Professional DevOps engineers routinely use the website *crontab.guru* to type out their asterisks and verify the English translation before committing it to a production server schedule.

9. Common Mistakes

  • Forgetting execute permissions: cron is not magic; it is bound by standard Unix file permissions. If you add /home/admin/script.sh to your crontab, but you forgot to execute chmod +x script.sh, cron will silently fail to execute the file every single time it tries.

10. Mini Project: Create an Automated Cleanup Script

Let's build a script that deletes temporary log files older than 7 days, and schedule it to run every Sunday at midnight.
  1. 1. nano log_cleanup.sh
  1. 2. Write the code:
sh
1234567891011
#!/bin/sh

# Target directory
TARGET="/tmp/old_logs"

# Ensure the script uses absolute paths for commands!
/usr/bin/find "$TARGET" -name "*.log" -type f -mtime +7 -exec rm -f {} \;

# Log the cleanup action
CURRENT_TIME=$(/bin/date +"%Y-%m-%d %H:%M:%S")
echo "[$CURRENT_TIME] Weekly cleanup executed successfully."
  1. 3. Make it executable: chmod +x logcleanup.sh
  1. 4. Open your schedule: crontab -e
  1. 5. Add the job (Run at 00:00 every Sunday/Day 0):
0 0 * * 0 /path/to/log
cleanup.sh >> /var/log/cleanup.log 2>&1
  1. 6. Save and exit. The system is now permanently automated.

11. Practice Exercises

  1. 1. Translate the following English requirement into exact Cron syntax: "Execute the database synchronization script exactly at 3:15 AM every weekday (Monday through Friday)."
  1. 2. Explain the "Cron Environment Trap". Why might a script containing the command aws s3 sync execute flawlessly when typed interactively by an administrator, but fail with "Command not found" when executed by cron?

12. MCQs with Answers

Question 1

An administrator edits their crontab file and inputs the schedule string */5 * * * *. How often will the associated shell script execute?

Question 2

When scheduling an automation script via cron, which redirection syntax is considered a mandatory best practice to ensure that both successful script outputs and catastrophic runtime errors are permanently recorded for forensic analysis?

13. Interview Questions

  • Q: A developer complains that a cron job they scheduled using crontab -e is failing to run. You verify the syntax is perfectly formatted as 0 5 * * * /opt/scripts/deploy.sh. Walk me through the two most common administrative oversights that cause a perfectly scheduled script to fail execution. *(Hint: Permissions and Paths).*
  • Q: Explain the structural syntax of the cron schedule string. If you needed a script to run ONLY during normal business hours (9:00 AM to 5:00 PM) on weekends (Saturday and Sunday), how would you construct the hour and day fields?
  • Q: Contrast the @reboot cron directive with managing a script via a systemd service file. While both can start a script on boot, why is systemd vastly superior for running permanent background web servers?

14. FAQs

Q: Can I run a cron job every 10 seconds? A: No. The cron daemon only checks its schedule once per minute. Minute * is the absolute minimum granularity. If you require a script to execute every 10 seconds, you must write a standard while true loop inside a script utilizing a sleep 10 command, and run that script permanently in the background.

15. Summary

In Chapter 13, we delegated absolute execution authority to the Unix operating system. We interfaced with the cron daemon via crontab -e, mastering the strict 5-field asterisk syntax to orchestrate precise time-based execution schedules. We secured our automated pipelines by redirecting disjointed stdout and stderr streams directly into persistent log files utilizing the >> log 2>&1 technique. Finally, we recognized and mitigated the environmental constraints of the cron daemon, strictly utilizing absolute execution paths to ensure our scripts execute flawlessly in the absence of a user's interactive profile variables.

16. Next Chapter Recommendation

Your script can run perfectly on a single machine. But modern architecture is rarely isolated to one server. To orchestrate a true cloud environment, we must integrate network intelligence. Proceed to Chapter 14: Networking and Remote Commands.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·