Stackademic

Stackademic is a learning hub for programmers, devs, coders, and engineers. Our goal is to…

Follow publication

Automating Tasks in Linux Using Cron Jobs and Shell Scripting

Kelvin Esosa
Stackademic
Published in
4 min readOct 27, 2023

--

The finest programmers not only identify the best answers to problems but also the simplest method to tackle them.

One of the best ways to make your life and job easier is to automate things. Some programmers I know automate even the most mundane processes in their everyday lives. E.g., Automating repetitive data entry tasks

We can achieve automation by writing shell scripts and executing them at a predetermined time using a cron job.

For a case study, we’ll do a simple task. We will create a backup script to backup files at 2 a.m. every day.

What’s Automation Anyway?

Automation refers to the process of automatically scheduling and running processes without the need for manual involvement. This can include simple chores like cleaning up log files as well as more involved processes like database backups. The beauty of automation is that it can save you time, decrease human error, and ensure that key tasks are completed consistently.

Shell Scripting

A shell script is a text file containing a series of commands that the shell interprets and executes sequentially. It’s like having a conversation with your Linux system, telling it precisely what to do. Shell scripts are often written in Bash, the default shell for most Linux distributions.

Cron Jobs

Cron is a time-based job scheduler in Linux. It allows you to run commands or scripts at specific intervals — be it every minute, hour, day, month, or any combination thereof. This simple concept can be a game-changer when it comes to automating routine tasks. Instead of manually setting an alarm, use cron jobs, your reliable time-based task schedulers. Cron jobs act as personal taskmasters, executing commands at specified intervals to free up your time for more entertaining tasks.

Examples of Cron Jobs

Here are a few examples of tasks you can automate with Cron:

  • Data Backup: Schedule regular backups of important files and databases.
  • Log Rotation: Rotate and compress log files automatically to keep them from taking up disk space.
  • System Updates: To keep your Linux distribution secure, enable automatic system updates.

Now let's get started with our task.

How to create a Basic Shell Script

Let’s whip up a basic script to automate the backup of files to a location. Create a file, say backup-script.sh, and add the following lines:

#!/bin/bash
# This is a daily backup script
# Source directory to backup
source_dir="/path/to/source"
# Destination directory to store backups
backup_dir="/path/to/backup"
# Assign a timestamp to the backup filename.
timestamp=$(date +"%Y%m%d%H%M%S")
# Name of the backup file
backup_file="backup_$timestamp.tar.gz"
# Create the backup
tar -czf "$backup_dir/$backup_file" "$source_dir"
# Check if the backup was successful
if [ $? -eq 0 ]; then
echo "Backup completed successfully: $backup_file"
else
echo "Backup failed."
fi
  • fimarks the end of the if-else statement.

Save the file and make it executable:

chmod +x backup-script.sh

This command indicates that you are granting yourself (the machine’s user) authorization to run the script.

Image by Author

You may now run it like any other command:

./backup-script.sh

Now, how do we run it without manually opening the terminal and typing the command ./backup-script.sh? That's where Cron can help us.

How to create a Cron Job

Let’s get hands-on. To create a Cron job, open your terminal and type:

crontab -e

This command launches the default text editor and accesses your crontab file. The flag -e means to edit. So we just say, “I would like to modify the cron table.”

Now, to schedule your backup routine, add the following line:

0 2 * * * /path/to/your/backup-script.sh
  • The 0 and 2 denote the minute and hour, respectively.
  • The * symbols in the remaining positions represent any day, any month, and any day of the week.

Save and exit the editor, and voilà! Your backup script will now run automatically at the specified time.

Conclusion

Automation is your best friend in the world of Linux because it saves time, reduces the risk of human error, and allows you to focus on more critical tasks. By harnessing the power of Cron jobs and Shell scripting, you can unlock a new level of efficiency in your Linux journey. So, the next time you find yourself contemplating a midnight backup session, remember that Linux has your back.

Happy automating!

Stackademic

Thank you for reading until the end. Before you go:

  • Please consider clapping and following the writer! 👏
  • Follow us on Twitter(X), LinkedIn, and YouTube.
  • Visit Stackademic.com to find out more about how we are democratizing free programming education around the world.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Published in Stackademic

Stackademic is a learning hub for programmers, devs, coders, and engineers. Our goal is to democratize free coding education for the world.

Written by Kelvin Esosa

Cloud Engineer || Technical Writer || DevOps

Write a response