
Note: This article is an original work by Liu Feng from Anya Technology. Please respect intellectual property rights. When sharing, please indicate the source. No plagiarism, adaptation, or unauthorized reproduction is accepted.
Introduction
In the world of Linux, how can you make your computer automatically back up data every night, clean temporary files every Monday morning, or check service status every minute without human intervention? The answer is crontab.
Crontab is a powerful and reliable scheduling tool for tasks, and it is a core skill that every Linux user and system administrator must master.
This article will guide you step by step from zero to mastery of crontab in the most detailed and friendly manner, covering basic syntax, practical operations, environment variables, log troubleshooting, and a production-level RMAN script for automating the cleanup of Oracle archive logs, making you an automation task master with ease.
01
Getting to Know Crontab—How Can My Computer Be “Disciplined”?
1
What are cron and crontab?
cron
It is a daemon that runs in the background of the Linux system.
You can think of it as a tireless “butler” holding a stopwatch and a task list.
It checks the task list every minute to see if there are any tasks to execute at that moment.
crontab
crontab
This term is short for “cron table”. It is a text file that records “who” (which user), “when” (specific time), and “what” (the command to execute).
We also use the term crontab to refer to the command that manages this file.
In simple terms
cron is the faithful butler that executes tasks, while the crontab file is the task list we write for the butler.
2
Why do we need crontab?
Automation
It allows repetitive and regular tasks (such as backups, cleanups, report generation) to be completed automatically by the computer, freeing your hands and time.
Off-Hours Execution
Tasks that are time-consuming and resource-intensive can be executed during low system load hours, avoiding disruption to normal work during the day.
Regular Monitoring
You can write scripts to have cron check every few minutes whether a website is accessible, whether the database connection is normal, and send email alerts when issues arise.
02
The Core of Crontab—
The “Five Star” Time Syntax
The core of crontab tasks is its time definition format. Each task line consists of two parts: time definition and the command to execute.
The time definition consists of five fields, commonly referred to as the “five stars”, separated by spaces.
* * * * * command_to_execute
┬ ┬ ┬ ┬ ┬
│ │ │ │ │
│ │ │ │ └───── Day of the week (0 - 7) (0 and 7 both represent Sunday)
│ │ │ └────────── Month (1 - 12)
│ │ └─────────────── Day (1 - 31)
│ └──────────────────── Hour (0 - 23)
└───────────────────────── Minute (0 - 59)
1
Meaning of Special Characters
After understanding the positions of these five fields, we also need to learn some special characters that make the time definitions very flexible.
* (Asterisk)
Represents “every”.
This is the most commonly used character.
, (Comma)
Used to list non-continuous time points.
-
0 8,12,18 * * * means “at 8:00, 12:00, and 18:00 every day”.
– (Dash)
Used to define a continuous time range.
-
0 9-17 * 1-5 means “at 0 minutes every hour from 9 AM to 5 PM, Monday to Friday”.
/ (Slash)
Used to define step size or frequency.
-
*/5 * * * * means “every 5 minutes”.
-
0 */2 * * * means “at 0 minutes every 2 hours (i.e., on the hour every two hours)”.
2
Practical Examples—From Simple to Complex
Let’s look at some real examples to deepen our understanding:
Execute backup script at 2:15 AM every day
15 2 * * * /home/user/scripts/backup.sh
Clean /tmp directory at 4:30 AM every Sunday
30 4 * * 0 /bin/rm -rf /tmp/*
Send monthly report at 10:00 AM on the 1st of every month
0 10 1 * * /home/user/scripts/send_report.sh
Check service status every hour on weekdays
0 * * * 1-5 /home/user/scripts/check_service.sh
Sync time every 10 minutes
*/10 * * * * /usr/sbin/ntpdate time.windows.com
03
Basic Operations of Crontab—How to Manage
Your Task List
Managing crontab tasks is mainly done through the crontab command with different options.
Important Note
Unless you are a system administrator and truly need to, never directly edit the /etc/crontab system file.
Please always use the crontab -e command to manage your own user-level scheduled tasks.
1
Edit Tasks (crontab -e)
This is the command you will use most frequently.
When you run it for the first time, the system may prompt you to choose a default text editor (like nano or vim).
crontab -e
Function
Opens a text editor specifically for your crontab file.
Operation
a. Write one scheduled task per line in the opened file.
b. The format is Minute Hour Day Month Week command.
c. Lines starting with # are comments and will not be executed.
d. After editing, save and exit. The cron daemon will automatically load your new task list without needing to restart any services.
2
View Tasks (crontab -l)
This command is used to quickly view which scheduled tasks you have set up.
crontab -l
Function
Prints the contents of your current crontab file to the screen. This is a read-only operation and is very safe.
3
Delete All Tasks (crontab -r)
Warning
This is a very dangerous command! Please use it with caution!
crontab -r
Function
Immediately deletes all scheduled tasks for your current user without any confirmation.
Once executed, your crontab file will be cleared.
Safety Advice
Before executing -r, it is best to back up your task list with the command crontab -l > crontab_backup.txt.
04
Advanced Practice—Building a Production-Level Oracle
RMAN Archive Cleanup Script
This is one of the most classic and critical applications of crontab in database operations.
Oracle databases in archive mode continuously generate archive logs, and if not cleaned up in time, they can quickly fill up disk space, causing the database to “hang” due to inability to archive.
We need an automated and robust strategy to regularly delete old archive logs.
Our Task
Automatically delete all Oracle archive logs that are older than 3 days and have been backed up at least once, every day at 1:00 AM.
Environmental Assumptions
-
Oracle User: oracle
-
Oracle SID: orcl
-
Oracle Environment Variable Script: /home/oracle/.bash_profile
-
Script and Log Storage Directory: /home/oracle/scripts
We will only use the officially recommended RMAN tool from Oracle and encapsulate it in a well-functioning Shell script.
1
Step 1: Write a Robust, Reusable RMAN
Invocation Script
This Shell script will serve as the entry point for our crontab task.
It not only simply calls RMAN but also includes essential elements for production environments such as logging, environment variable loading, and error checking.
# Log in as oracle user
su - oracle
# Create script directory (if it does not exist)
mkdir -p /home/oracle/scripts/logs
# Create Shell script file
vi /home/oracle/scripts/rman_cleanup_archive.sh
Write the following content in the script
#!/bin/bash
# =================================================================
# Script Name: auto_delete_archivelog.sh
# Description: Automatically delete expired Oracle archive logs using RMAN
# Author: DBA Team
# Date: 2025-11-13
# =================================================================
# --- 1. Set environment variables ---
# For RAC environments, set the SID of one instance only
source ~/.bash_profile
# If your environment is configured with oraenv, it will be more convenient
# . oraenv <<< $ORACLE_SID
# --- 2. Define log file ---
LOG_DIR="/home/oracle/scripts/logs"
LOG_FILE="${LOG_DIR}/delete_archive_$(date +%Y%m%d_%H%M%S).log"
mkdir -p $LOG_DIR # Ensure log directory exists
# --- 3. Main execution logic ---
echo "=================================================" | tee -a ${LOG_FILE}
echo "Script execution started: $(date +"%Y-%m-%d %H:%M:%S")" | tee -a ${LOG_FILE}
echo "ORACLE_SID: ${ORACLE_SID}" | tee -a ${LOG_FILE}
echo "ORACLE_HOME: ${ORACLE_HOME}" | tee -a ${LOG_FILE}
echo "-------------------------------------------------" | tee -a ${LOG_FILE}
# Execute commands using RMAN's "here document" syntax
rman TARGET / <<< EOF >> ${LOG_FILE}
CROSSCHECK ARCHIVELOG ALL;
DELETE NOPROMPT EXPIRED ARCHIVELOG ALL;
DELETE NOPROMPT ARCHIVELOG ALL COMPLETED BEFORE 'SYSDATE-0.1';
LIST ARCHIVELOG ALL;
EOF
RMAN_EXIT_CODE=$?
echo "-------------------------------------------------" | tee -a ${LOG_FILE}
if [ ${RMAN_EXIT_CODE} -eq 0 ]; then
echo "RMAN script executed successfully." | tee -a ${LOG_FILE}
else
echo "Error: RMAN script execution failed, exit code: ${RMAN_EXIT_CODE}" | tee -a ${LOG_FILE}
fi
echo "Script execution ended: $(date +"%Y-%m-%d %H:%M:%S")" | tee -a ${LOG_FILE}
echo "Script log directory: ${LOG_FILE}"
echo "=================================================" | tee -a ${LOG_FILE}
exit ${RMAN_EXIT_CODE}
2
Step 2: Grant Execution Permissions to the Script
chmod +x /home/oracle/scripts/rman_cleanup_archive.sh
3
Step 3: Add the Script to Crontab
Now, we can confidently hand over this robust Shell script to crontab for scheduling.
# Still execute as oracle user
crontab -e
In the opened editor, add the following line:
# =====================================================================
# Oracle DB Maintenance Tasks
# =====================================================================
# At 01:00 on every day, run the RMAN archive log cleanup script.
0 1 * * * /home/oracle/scripts/rman_cleanup_archive.sh
Why is there no need for > /dev/null 2>&1 here?
Because our Shell script has already perfectly handled log redirection internally!
All output from the script will be automatically logged in the log file in the /home/oracle/scripts/logs/ directory.
The benefits of this approach are:
Log Separation
The scheduling logs from crontab and the execution logs from RMAN are separated, making troubleshooting clearer.
Log Archiving
A new log file is generated every day, making it easier to trace historical records.
Error Capture
The internal if statement in the script can determine whether RMAN executed successfully and can be extended to include email alerts and other advanced features.
05
Common “Traps” for Beginners and Best Practices
Crontab may seem simple, but there are many “pits” in actual use.
Understanding and avoiding them is key to ensuring stable task operation.
1
Trap 1: Environment Variable Issues
Problem
You can run scripts normally in the terminal, but they fail when placed in crontab.
Reason
When cron executes tasks, it loads a very minimal environment variable.
It does not know about the complex PATH, ORACLE_HOME, and other variables you set in .bashrc or .profile.
Solution
-
Use Absolute Paths
In the crontab command, use absolute paths for all commands and files involved.
-
Load Environment Variables in the Script (Best Practice)
As we did in the Oracle script example, manually source the required environment variable files at the beginning of the script.
2
Trap 2: Special Meaning of the % Character
Problem
The % character included in the command mysteriously disappears or causes the task to fail.
Reason
In crontab, % is a special character that represents “newline”.
Solution
If your command indeed requires the % character (for example, in the date command formatting), you must escape it (\%).
3
Trap 3: Command Output and Logs
Problem
The script executed, but how do you know the result?
Or, the script produced a lot of output, filling the system administrator’s mailbox.
Reason
By default, cron sends any standard output (stdout) and standard error output (stderr) generated during task execution to the task owner via email.
Solution (Output Redirection)
-
Completely Ignore All Output (Silent Execution)
… > /dev/null 2>&1
-
Log Output to a Log File (Best Practice)
… >> /path/to/logfile.log 2>&1
06
Troubleshooting Guide—Why Is My Cron
Not Working?
This is the ultimate question every crontab novice encounters: “My command runs fine in the terminal, why does it not respond when placed in crontab?”
Or more confusingly: “The cron log clearly shows execution, why is the task still unsuccessful?”
Don’t worry, this is usually not a “mystical” problem.
Let’s learn how to become a “detective” of cron tasks through a real “silent failure” case.
1
Real Case: An “Apparent Execution, but Actually Failed”
Oracle Cleanup Task
Case Background
We configured a crontab task for the oracle user, hoping to execute the archive cleanup script rman_cleanup_archive.sh every minute for quick testing.
Collected “Contradictory” Clues
-
Clue A: Crontab Configuration (crontab -l)
*/1 * * * * /home/oracle/scripts/rman_cleanup_archive.sh
The configuration is correct, meaning “execute the script every minute”.
Clue B: System Log (/var/log/cron)
Nov 16 14:22:01 anyadb1 CROND[6803]: (oracle) CMD (/home/oracle/scripts/rman_cleanup_archive.sh)
Nov 16 14:23:01 anyadb1 CROND[6815]: (oracle) CMD (/home/oracle/scripts/rman_cleanup_archive.sh)
Imagine this scenario: You log into a Linux server, ready to create a temporary file, but are met with a harsh refusal from the system.
-
Clue C: RMAN Log (/home/oracle/scripts/logs)
[oracle@anyadb1 logs]$ ll
total 32
-rw-r--r-- 1 oracle oinstall 10982 Nov 16 14:08 delete_archive_20251116_140812.log
-rw-r--r-- 1 oracle oinstall 2305 Nov 16 14:09 delete_archive_20251116_140909.log
-rw-r--r-- 1 oracle oinstall 2305 Nov 16 14:10 delete_archive_20251116_141022.log
-rw-r--r-- 1 oracle oinstall 2305 Nov 16 14:11 delete_archive_20251116_141101.log
-rw-r--r-- 1 oracle oinstall 2305 Nov 16 14:17 delete_archive_20251116_141743.log
No new RMAN logs!
-
Clue D: Results of Manual Execution (Decisive Evidence)
To verify the script itself, we executed the complete command from crontab directly in the terminal as the oracle user.
[oracle@anyadb1 scripts]$ /home/oracle/scripts/rman_cleanup_archive.sh
-bash: /home/oracle/scripts/rman_cleanup_archive.sh: Permission denied
When executed manually, we received a clear Permission denied error.
-
Clue E: User Mailbox (mail)
We checked the oracle user’s mailbox, hoping to find the error report sent by cron.
[oracle@anyadb1 scripts]$ mail
No mail for oracle
The mailbox is empty! No error letters.
Core Contradiction
Why does the system log show that cron executed the command, but manual execution indicates insufficient permissions, and there are no email notifications?
2
The “Detective’s” Investigation and Analysis
Analysis 1: The True Meaning of CMD Logs
The CMD (…) logs recorded in /var/log/cron actually mean: “the cron daemon successfully forked a child process and let this child process execute /bin/sh -c ‘your_command’”.
It records the success of the scheduling behavior, not the final execution result of the scheduled command.
Analysis 2: The Root Cause of Permission Denied
The result of manual execution is the most honest.
Permission denied clearly tells us that the oracle user does not have permission to execute the file /home/oracle/scripts/rman_cleanup_archive.sh.
We verify with ls -l:
ls -l /home/oracle/scripts/rman_cleanup_archive.sh
# Output:
# -rw-r--r-- 1 oracle oinstall 1234 Nov 16 14:20 rman_cleanup_archive.sh
This rw-r–r– (644) permission does not have the x (execute) bit at all.
Therefore, when the shell tries to execute it, the kernel directly refuses.
Analysis 3: The Mystery of the “Silent Mailbox”
Why is there such a clear Permission denied error, yet no mail is sent?
This is usually due to the minimal installation strategy of modern Linux systems.
To keep the system lean, many distributions do not install mail transfer agents (MTAs) like postfix or sendmail by default.
-
Workflow
The cron daemon attempts to call the sendmail program to send mail when it captures the script’s error output (Permission denied).
-
Problem
If there is no sendmail or similar MTA service in the system, the cron sending request will fail.
It’s like dropping a letter into a nonexistent mailbox; the letter is “lost” and will not reach your mail inbox.
Conclusion
The mail notification feature of cron is a fragile and dependent feature.
We must never rely on it as the sole troubleshooting method.
3
Case Resolution and Fix
Step 1: Establish a Reliable Logging Mechanism (Best Practice)
Since we cannot rely on mail, we must let the script “fend for itself” and actively log.
Modify the crontab entry to redirect all output to a specified file.
# Execute as oracle user
crontab -e
Modify the crontab content as follows:
*/1 * * * * /home/oracle/scripts/rman_cleanup_archive.sh >> /home/oracle/scripts/logs/cron_run.log 2>&1
-
>> /path/to/logfile.log
Appends standard output to the log file.
-
2>&1
Redirects standard error output (stderr, file descriptor 2) to standard output (stdout, file descriptor 1), so that both normal information and error information are written to the log file.
This way, we can capture the information we really want
[oracle@anyadb1 logs]$ cat /home/oracle/scripts/logs/cron_run.log
/bin/sh: /home/oracle/scripts/rman_cleanup_archive.sh: Permission denied
/bin/sh: /home/oracle/scripts/rman_cleanup_archive.sh: Permission denied
/bin/sh: /home/oracle/scripts/rman_cleanup_archive.sh: Permission denied
/bin/sh: /home/oracle/scripts/rman_cleanup_archive.sh: Permission denied
/bin/sh: /home/oracle/scripts/rman_cleanup_archive.sh: Permission denied
Step 2: Grant Correct Permissions to the Script (Root Cause Fix)
This is the fundamental solution to the problem.
# Execute as oracle user or root user
chmod +x /home/oracle/scripts/rman_cleanup_archive.sh
Verify:
# Output should now be:
[oracle@anyadb1 logs]$ ls -l /home/oracle/scripts/rman_cleanup_archive.sh
-rwxr-xr-x 1 oracle oinstall 1836 Nov 16 14:10 /home/oracle/scripts/rman_cleanup_archive.sh
Now, the script has executable permissions.
In this way, whether the script executes successfully or fails, we can always find a complete execution record in a fixed place (cron_run.log), completely freeing ourselves from dependence on the system mail service.
07
Conclusion
Crontab is the cornerstone of automation in Linux systems. At first glance, its “five star” syntax may seem daunting, but once you master its core rules and best practices, it will become one of your most powerful tools.
Through practical exercises like automating the cleanup of Oracle archive logs, we not only learned how to use crontab but also understood how to write robust and reliable automation scripts in real operational scenarios.
Remember, using absolute paths, properly handling environment variables, and meticulous log management are the three golden rules to ensure your scheduled tasks run stably over the long term.
Final Note
If you want to systematically enhance your Shell automation programming skills, I recommend checking out Liu Feng’s Linux series courses.
The course content progresses step by step, from basic if/for/while loops to text processing tools like sed and awk, and then to writing production-level automation operation scripts, helping you build a complete Shell automation knowledge system and truly achieve “let the machine work for you”.

Author Introduction

Hello everyone, I am Liu Feng, the founder of Anya Technology & Senior Database Technology Instructor, focusing on PostgreSQL, domestic database operation and migration, database performance optimization, and other directions.
As an officially authorized lecturer of the PG China branch and a PostgreSQL ACE certified expert, I am actively involved in frontline project practice, with over 10 years of experience in large database management and optimization, having deeply participated in database performance tuning and migration projects in various industries such as telecommunications, finance, and government.
Welcome to follow me and explore the infinite possibilities of databases together, with no limits on technical exchanges!
📌 If you find this helpful, remember to like, bookmark, and share to support me, and don’t forget to follow me for more database insights~
Anya Smart Data Workshop|What We Can Do
Whether you are the technical leader of a business system or the first responder in the data department, we can provide you with reliable support:
-
Database Type Support
Oracle / MySQL / PostgreSQL / SQL Server and other mainstream databases
-
Core Service Content
Performance optimization / Fault handling / Data migration / Backup recovery / Version upgrade / Patch management
-
Systematic Support
In-depth inspection / High availability architecture design / Application layer compatibility assessment / Operation and maintenance tool integration
-
Specialized Capability Supplement
Customized course training / Client team coaching / Complex problem collaborative troubleshooting / Emergency rescue support
📮 If you have an unremovable table, a query that won’t run, or an unclear upgrade risk, feel free to reach out to us for a chat.
END
Keyword Response (Visible in Corresponding Articles):
oracle, mysql, pg, postgresql, sql, performance optimization, fault handling, data migration, backup recovery, version upgrade, patch management, in-depth inspection, solutions, architecture design……

Add WeChat friends for 1-on-1 consultation
\ | /
★
Move your fingers
Give [Anya Smart Data Workshop] a star mark~
So you won’t lose me~
Remember to add a star mark!

