crontab - Linux


Overview

The crontab command in Linux is used for editing the cron table that contains commands and scripts scheduled to run at specific times. It allows users to schedule tasks that should repeat periodically at fixed times, dates, or intervals. Typically utilized for system maintenance or administration tasks like backups, updates, and monitoring, crontab is fundamental in automating and managing time-based jobs.

Syntax

The basic syntax for the crontab command is as follows:

crontab [options] [file]
  • file: Specifies the filename of the crontab to install as the user’s current crontab. If no file specified, crontab uses standard input.

Options/Flags

  • -e: Edit the current crontab using the editor specified by the VISUAL or EDITOR environment variable.
  • -l: List the current crontab on standard output.
  • -r: Remove the current crontab.
  • -i: Provides a prompt before removing the crontab. It is used with -r.
  • -u <user>: Specifies the crontab belongs to the user. Must be superuser to use this option.

Examples

  1. Editing Crontab:
    Open your crontab file for editing:

    crontab -e
    
  2. Listing Crontab:
    To display your current crontab entries:

    crontab -l
    
  3. Removing Crontab:
    Remove your current crontab with a confirmation prompt:

    crontab -ri
    
  4. Scheduling a Job:
    To run a script at 5 AM daily:

    0 5 * * * /path_to_script/script.sh
    

Common Issues

  • Editor Not Configured: If the EDITOR environment variable is not set, crontab -e might fail. Set it by export EDITOR=nano or your preferred editor.
  • Miscalculating Time: Users often mistake the time settings which results in scripts executing at unexpected times.
  • Permission Issues: Running scripts that require higher privileges might fail if the crontab is set for a non-privileged user.

Integration

crontab can be effectively combined with shell scripts to automate complex tasks. Here’s an example of a cron job that dumps a PostgreSQL database and pipes it into a gzip file daily:

0 2 * * * pg_dump dbname | gzip > /path_to_backup/db-$(date +\%Y-\%m-\%d).gz

This command combines pg_dump, gzip, and date to create a dated backup file of a database.

  • at: Execute commands at a later time.
  • anacron: Like cron, but does not assume that the system is running continuously.
  • watch: Execute a program periodically, showing output fullscreen.

For more details or complex scenarios, consult the official documentation or the man pages (accessible via man crontab).