📜  linux 中的 crontab - Shell-Bash (1)

📅  最后修改于: 2023-12-03 14:43:56.419000             🧑  作者: Mango

Crontab in Linux - Shell/Bash

Introduction

Crontab is a command-line utility in Linux that allows programmers and system administrators to schedule recurring tasks or scripts to be executed at a specific time or interval. It stands for "cron table" and is typically used for automating repetitive tasks, such as backups, system maintenance, data processing, and more.

This guide aims to provide a comprehensive overview of using Crontab in Linux with a focus on the Shell/Bash scripting language.

Prerequisites

Before we dive into the details, ensure that you have:

  • A Linux system with Crontab installed (usually pre-installed on most distributions).
  • Basic understanding of Shell/Bash scripting.
Crontab Syntax

The syntax for using Crontab to schedule tasks follows a specific pattern:

* * * * * command_to_be_executed
|-|-|-|-|-|
| | | | | |
| | | | | +----- Day of the Week (0 - 6) (Sunday = 0)
| | | | +------- Month (1 - 12)
| | | +--------- Day of the Month (1 - 31)
| | +----------- Hour (0 - 23)
| +------------- Minute (0 - 59)
+--------------- Every minute/hour/day/month/day of the week
  • Each asterisk (*) represents a wildcard value, meaning the task will be executed for every possible value in that position. For example, if all fields have asterisks, the task will run every minute of every hour, every day, every month, and every day of the week.

  • Specific values can be provided for each field to schedule tasks for specific times or dates.

Managing Crontab Entries

Crontab entries can be managed using the crontab command:

  • To view/edit the Crontab file for the current user, use:
    $ crontab -e
    
  • To view the existing Crontab entries, use:
    $ crontab -l
    
  • To remove all Crontab entries, use:
    $ crontab -r
    
  • To install a new Crontab file from a text file, use:
    $ crontab filename
    
Examples
  1. Run a script every day at 5:30 AM:
    30 5 * * * /path/to/script.sh
    
  2. Execute a command every hour on weekdays:
    0 * * * 1-5 command_to_execute
    
  3. Run a script every 15 minutes:
    */15 * * * * /path/to/script.sh
    
  4. Schedule a task to run on specific days and times:
    0 12 * 3,6,9,12 1,5 /path/to/script.sh
    
Conclusion

Crontab is a powerful tool for automating tasks in Linux. By understanding its syntax and using it with Shell/Bash scripting, programmers can schedule and execute scripts at specific times and intervals. With the examples provided, you can now start using Crontab effectively to automate your routine tasks on a Linux system.