Learn Shell Scripting basics and Cron jobs

Shell scripting is one of the most powerful skills in Linux. It allows you to automate tasks, manage systems efficiently, and handle repetitive work with ease. Whether you want to schedule backups, process files in bulk, or set up system monitoring, shell scripts can save time and reduce errors.

On Linux, the most common shell used for scripting is Bash, short for Bourne Again SHell. Bash is available on almost all Linux distributions by default, making it the go-to tool for writing scripts.

In this guide, you will learn the basics of Bash scripting, how to use variables, conditionals, and loops, how to schedule scripts using cron and at, and how to handle errors in your automation tasks. Each section includes practical examples to help you start writing your own scripts with confidence.


Bash Scripting Basics

A Bash script is simply a text file that contains a series of commands. Instead of typing each command into the terminal manually, you can put them into a file and run that file.

To begin writing your first script, create a script file using the vim or nano editor:

nano hello.sh

Then write the following inside the file:

#!/bin/bash
echo "Hello, this is my first shell script."
Creating First Shell Script
Creating First Shell Script

Now save and exit out of the editor by pressing Ctrl + X, then Y, and then Enter.

Make the script executable using the chmod command:

chmod +x hello.sh

Finally, run the script:

./hello.sh
Executing The Script
Executing The Script

You should see the output message printed in the terminal. Every script should start with the shebang line #!/bin/bash, which tells Linux to use the Bash interpreter.

Using Shell Variables

Variables in Bash store values that can be reused in your script. There is no need to declare types.

Here’s how to assign and use variables:

#!/bin/bash
name="Alice"
echo "Hello, $name"

Create this as a script using the editor of your choice. For example, use nano greet.sh to open a new script file, paste the code, and save and exit out of the editor.

Executing Script With A Variable
Executing Script With A Variable

Do not put spaces around the equals sign when assigning a value. To use the value of a variable, prefix it with a dollar sign $.

You can also use command substitution to store the output of a command in a variable:

current_date=$(date)
echo "Today is $current_date"

To execute:

chmod +x greet.sh
./greet.sh

Conditionals in Shell Scripts

Conditional statements allow your script to make decisions. The most common conditional structure is the if statement.

#!/bin/bash

read -p "Enter a number: " number

if [ $number -gt 10 ]; then
  echo "The number is greater than 10."
else
  echo "The number is 10 or less."
fi

Use -eq for equal, -ne for not equal, -lt for less than, -le for less than or equal, and -ge for greater than or equal.

Using Conditionals In Shell Scripts
Using Conditionals In Shell Scripts

Using Loops in Bash

Loops help you repeat tasks. Bash supports several types of loops, such as for, while, and until.

A for loop:

#!/bin/bash

for file in *.txt
do
  echo "Found file: $file"
done

A while loop:

#!/bin/bash

counter=1
while [ $counter -le 5 ]
do
  echo "Count: $counter"
  ((counter++))
done

These structures are helpful when processing files, automating tasks, or checking conditions multiple times.


Writing Linux Scripts: Putting It All Together

Here is a more complete example. This script checks if a file exists and backs it up:

#!/bin/bash

filename="important.txt"

if [ -f "$filename" ]; then
  cp "$filename" "$filename.bak"
  echo "Backup created for $filename"
else
  echo "$filename does not exist"
fi

You can place this script in your ~/bin directory and add that directory to your PATH to make it runnable from anywhere.


Automating Scripts with Cron Jobs

To run scripts automatically at scheduled times, use cron. Cron is a time-based job scheduler built into most Linux systems.

To open the crontab (cron table) for the current user:

crontab -e
Running Crontab
Running Crontab

Add a line to schedule a script. For example, to run backup.sh every day at 2 AM:

0 2 * * * /home/user/scripts/backup.sh

Each cron job follows this format:

minute hour day month day-of-week command

After saving the file, the system will run your script based on the schedule.

To list all cron jobs:

crontab -l

To remove them:

crontab -r

Make sure your script is executable and has the right permissions. Also, include full paths to files and commands in scripts run by cron, since the environment is limited.


Running One-Time Tasks with at Command

The at command lets you schedule one-time tasks in the future.

First, make sure it is installed:

sudo apt install at

To schedule a task:

echo "/home/user/scripts/update.sh" | at 5:30 PM
Automating Task Using The At Command
Automating Task Using The At Command

To view scheduled tasks:

atq

To remove a task:

atrm <job-number>

This tool is useful when you need to delay a task or run something only once without setting up a recurring cron job.


Bash Error Handling

It is important to handle errors, so your scripts do not fail silently or cause problems.

To stop the script if any command fails:

#!/bin/bash
set -e

This tells the script to exit immediately if any command returns a non-zero exit status.

You can also check individual command success with if:

if cp file1.txt file2.txt; then
  echo "Copy succeeded"
else
  echo "Copy failed"
fi

Use exit to manually stop a script with a specific error code:

if [ ! -f "input.txt" ]; then
  echo "Error: input.txt not found"
  exit 1
fi

Logging errors and using set -euo pipefail can make scripts more robust in production environments.


Summary

Shell scripting is an essential Linux skill that lets you automate repetitive tasks, process data, and manage systems efficiently. You have learned how to write basic Bash scripts with variables and comments, Use conditionals and loops to make decisions and repeat actions, schedule tasks with ‘cron’ and ‘at’, and handle errors and make scripts more reliable.

With these tools, you can create custom automation for backups, updates, monitoring, and many other tasks. Start small, test your scripts, and build on what you learn.

In the next article, we will see in depth about Networking on Linux.