Run script automatically with Cron on Linux

- 👤 Andrés Cruz

🇪🇸 En español

Run script automatically with Cron on Linux

Crons are process managers that run in the background at specific time intervals according to how they are configured; they are widely used for performing scheduled backups.

As users, we can automate tasks with BASH commands (for example, to execute a script like a .sh); this way we can have complete administration of a system; it is not only possible to use .sh to utilize a Cron, but any type of BASH command can also be used (for example, to execute a PHP file); it all depends on what you want to do.

One of the things I like most about Linux is that practically everything can be automated. There is always some function, configuration, or tool that allows you to forget about repetitive tasks: from mounting units, running checks, generating logs, or launching scripts without manual intervention.
In this article, I am going to explain how to execute a script automatically in Linux using cron, but also when it is not advisable to use it and what real alternatives exist, based on what I have used myself in real Linux systems.

Task automation in Linux: why cron remains essential

When we talk about automation in Linux, cron remains the de facto standard. It’s not new, it’s not modern, but it works reliably and predictably on both desktop systems and servers.

Cron allows:

  • Executing scripts at time intervals
  • Automating maintenance tasks
  • Launching processes without depending on the user

In my case, cron has been key for periodic tasks, but I also learned —sometimes the hard way— that not all automations fit well in cron.

What is cron and how does it work in Linux?

What is a cron job

A cron job is a scheduled task that the system executes automatically following a defined schedule (minute, hour, day, month, etc.). These tasks are defined in a file called crontab.

Differences between Cron and Crontab

Although it might seem like we are indicating synonyms when we refer to one or the other, these are two independent elements, where Cron is a process and the other is a text file that we customize with the rules we will explain later.

In summary:

  • cron is the service that executes the tasks
  • crontab is the file where they are defined

Each user can have their own crontab, including root, which is important when the script needs elevated permissions.

Cron is a daemon (service)

Cron is a daemon, also known as a service, and therefore it is only started once, generally with the system boot itself; upon starting and at regular intervals, it checks if it has something to do, a task known as a job, which is what we configure, and compares it with the system date to see if there are coincidences between the scheduled time in the crontab and the system time.

How to execute a script automatically with cron in Linux

Prerequisites: permissions, shebang, and absolute paths

This is where many people fail. I failed at first too.

Before using cron, your script must:

  • Have execution permissions:
chmod +x script.sh

Have a correct shebang:

#!/bin/bash

Use absolute paths, never relative ones

Cron does not load your user environment, so assuming paths or variables usually leads to silent errors.

Creating a cron job step by step: Crontab is a file in our Linux

Cron is the process manager; Cron reads a plain text file called Crontab where a list of commands created by the user to be executed is saved; the syntax for creating one of these scheduled tasks is very simple:

# ┌───────────── Minute (0 - 59)
# │ ┌─────────── Hour (0 - 23)
# │ │ ┌───────── Day of the month (1 - 31)
# │ │ │ ┌─────── Month (1 - 12)
# │ │ │ │ ┌───── Day of the week (0 - 7, 0 and 7 are Sunday)
# │ │ │ │ │
# * * * * * command_to_be_executed

Basic format of a task in the Crontab: Adding tasks to the Crontab

Before using cron, your script must:

  • Have execution permissions:
  • chmod +x script.sh
  • Have a correct shebang:
  • #!/bin/bash
  • Use absolute paths, never relative ones

Cron does not load your user environment, so assuming paths or variables usually leads to silent errors.

Basically, a CRON consists of two halves:

  • The time at which the Crontab task will be executed; it is composed of operators and is extremely versatile:
    • Every minute: In intervals between 0 and 59.
    • Every hour: In intervals between 0 and 23.
    • Every day: In intervals between 0 and 31.
    • Every month: In intervals between 0 and 12 (0==12 and 12 == December).
    • Every day of the week: In intervals between 0 and 7 (0==7 and 7 == Sunday).
  • The BASH command: /full/path/to/script.sh

As you can see, these are duration blocks ranging from minutes to days of the week and month; if an asterisk is left, it means that the Cron runs every minute, hour, day of the month:

* * * * * /path/to/script.sh

Executes the script.sh every minute, of every hour, of every day of the month, of every week; in other words, Cron executes the script every minute of the 365 days of the year.

To execute a .sh at certain intervals, we can do something like the following:

1 2 3 4 5 /path/to/script.sh

If the .sh receives parameters:

1 2 3 4 5 /path/to/script.sh p1 p2 ... pn

Where p1, p2, ... pn are the parameters that the .sh receives.

Use of operators in a Crontab task

With operators, it is possible to specify multiple values in a field; there are three possible values:

  • The asterisk (*): This operator covers all possible values; an asterisk in a minute field is equal to executing the script every minute.
  • The comma (,): This operator allows specifying a list of values; for example, if we want to execute a command on Mondays and Wednesdays: "1,3" in the days field.
  • The hyphen (-): This operator specifies a series of values in a grouped manner with a lower and an upper bound; for example, if we wanted to execute a command from Monday to Friday, we could place the following value in the day field: "1-5", which is equivalent to 1,2,3,4,5.

Adding a task for execution

We already saw what the basic format of a Cron looks like, now the interesting part is: How do we add a Cron or our task for execution?

Open our console or terminal:

linux console

Run the following command:

Crontab -e 
linux console editing crontab with vi

Through a console editor; VI, VIM, nano, or any other you have installed, add the task to the Crontab; for example:

0 22 * * 1-5 /home/fedora/sh/backup.sh

If you wish to see the list of Crontab tasks in the system:

Crontab -l

Examples of Crontab tasks: Time intervals

If we want to execute a Crontab task every 5 minutes:

*/5 * * * * /home/fedora/sh/backup.sh

If we want to execute a Crontab task every 10 minutes:

*/10 * * * * /home/fedora/sh/backup.sh

If we want to execute a Crontab task every 20 minutes:

*/20 * * * * /home/fedora/sh/backup.sh

If we want to execute a Crontab task every 30 minutes:

*/30 * * * * /home/fedora/sh/backup.sh

If we want to execute a Crontab task every 40 minutes:

*/40 * * * * /home/fedora/sh/backup.sh

If we want to execute a Crontab task every 50 minutes:

*/50 * * * * /home/fedora/sh/backup.sh

If we want to execute a Crontab task every 60 minutes:

*/60 * * * * /home/fedora/sh/backup.sh

I think the idea is clear; you simply need to vary the number of minutes in the first position so that our Cron does the rest for us.

If we want to execute a Crontab task at 10 in the morning:

0 10 * * * /home/fedora/sh/backup.sh

If we want to execute a Crontab task at 2:15 in the afternoon every day:

15 14 * * * /home/fedora/sh/backup.sh

If we want to execute a Crontab task at 2:15 in the afternoon every day except weekends (Monday to Friday):

15 14 * * 1-5 /home/fedora/sh/backup.sh

If we want to execute a Crontab task at 2:15 in the afternoon every Sunday:

15 14 * * 0 /home/fedora/sh/backup.sh

or

15 14 * * 7 /home/fedora/sh/backup.sh

or

15 14 * * sun /home/fedora/sh/backup.sh

If we want to execute it on October 21st at 7:21:

21 7 21 10 * /home/fedora/sh/backup.sh

If we want to perform a backup every day at eight at night and save a log with possible errors when executing the Crontab:

0 20 * * * /home/fedora/sh/backup.sh >> /home/fedora/sh_backup/cron_ruas.log 2>&1

How to execute PHP periodically with Cron on a Linux server?

To execute a php file at certain intervals, we can use the following command:

php /var/www/html/test/test.php

This possibility is interesting; recalling a past article:

How to connect to Twitter and send tweets with PHP? we saw how to connect an application written in PHP with the Twitter API and thus be able to perform many tasks or operations; basically, we sent a tweet; now we could automate the execution of this PHP script to send the tweets:

*/5 * * * * php /var/www/html/twitter/sendtweets.php

To send tweets every five minutes.

Considerations

Remember to change the file permissions so it can be executed by the Cron manager:

chmod a+x /home/fedora/sh/backup.sh

It may be necessary to restart the Cron service after adding a task:

service crond restart

Creating a cron job step by step

Edit the crontab:

crontab -e

Add a line like this:

*/5 * * * * /full/path/to/script.sh

This will execute the script every 5 minutes.

When I first tried it, the script wasn't running… and the problem wasn't cron, but that the script worked in the terminal but not in cron because of the environment.

Practical examples of cron for bash scripts

Execute a script at the start of the day:

0 6 * * * /path/to/script.sh

Execute every hour:

0 * * * * /path/to/script.sh

Execute every Sunday:

0 3 * * 0 /path/to/script.sh

Common errors when executing scripts with cron (and how to fix them)

Cron does not execute the script

This is a classic. In my experience, it's usually due to:

  • Lack of permissions
  • Incorrect paths
  • Non-existent environment variables

Quick fix: run the script exactly as cron would.

Problems with environment variables

Cron does not load .bashrc or .profile. If your script depends on variables, define them within the script itself or in the cron job line.

Where to see cron logs

Depending on the distribution:

  • /var/log/syslog
  • /var/log/cron
  • journalctl -u cron

Checking logs saved me hours of frustration more than once.

Executing scripts automatically when starting Linux

This is where cron is not always the best option.

Many times I didn't need to schedule a task, but rather have the script run as soon as the system started, for example, to mount units or launch initial checks.

When cron is not the best option

  • Scripts that must run only once at boot
  • Tasks that depend on the initial state of the system
  • Processes that don't make sense in intervals

Executing scripts at boot using rc.local

A simple and effective solution is rc.local.

File:

/etc/rc.local

Typical content:

#!/bin/sh -e sh /path/to/script.sh exit 0

In Fedora, for example, this file does not exist by default, but it can be created and works without problems. When I used it for the first time, I was surprised by how simple and effective it was for certain cases.

Modern alternative: systemd

Today, systemd is the most correct option for persistent services. It is more verbose, but also more robust.

Ideal if:

  • The script must run as a service
  • You need status control
  • You work on modern servers

Cron vs rc.local vs systemd: which option to choose in each case

  • Case    Best option
  • Periodic tasks    cron
  • Script at startup    rc.local
  • Complex services    systemd

Not everything should be solved with cron. Understanding this makes the difference between a functional system and a fragile one.

Best practices for automating scripts in Linux

Use absolute paths

  • Always log the script's output
  • Test the script outside of cron
  • Do not assume user environment
  • Document what each task does

These practices are born from real errors, not theory.

Frequently asked questions about cron and automation in Linux

  • How to execute a script automatically in Linux?
    • Using cron for periodic tasks or rc.local/systemd for startup scripts.
  • What permissions does a script need for cron?
    • Execution permission and access to the resources it uses.
  • Why doesn't cron execute my script?
    • Usually due to incorrect paths or environment variables.
  • Where to see cron logs?
    • In syslog, cron.log, or via journalctl.

Conclusion

Cron remains an indispensable tool for executing scripts automatically in Linux, but it is not the only one nor always the best. In my experience, combining cron with rc.local or systemd depending on the case is the cleanest and most efficient way to automate a Linux system without unnecessary complications.

I agree to receive announcements of interest about this Blog.

Cron processes are process managers that run in the background at regular intervals, depending on how we configure them. We'll see how to use them, their definitions, common examples, and errors when using them.

| 👤 Andrés Cruz

🇪🇸 En español