Automating Daily Tasks in Linux with Shell Scripts and Cron

ยท

3 min read

Automating Daily Tasks in Linux with Shell Scripts and Cron

As a DevOps engineer, one of your responsibilities is to automate tasks to save time and increase efficiency. In Linux, shell scripts and cron can help you achieve this goal.

In this post, we'll cover three tasks that you can automate using shell scripts and cron: creating directories, backing up your work, and user management.

Task 1: Creating Directories with a Bash Script

The first task is to create multiple directories with a dynamic name. To achieve this, we'll use a bash script that takes three arguments: directory name, start number of directories, and end number of directories.

Here's the script:

#!/bin/bash

dir_name=$1
start=$2
end=$3

for i in $(seq $start $end)
do
  mkdir "$dir_name$i"
done

Let's say you want to create 50 directories with the prefix "day". You can execute the script like this:

./createDirectories.sh day 1 50

This will create 50 directories named "day1", "day2", ..., "day50".

Task 2: Backing Up Your Work

The second task is to create a backup of your work. Backups are important to prevent data loss in case of system failures or errors. We can create a shell script that creates a compressed archive of a specified directory and stores it in a backup directory.

Here's the script:

#!/bin/bash

backup_dir="/path/to/backup/directory"
source_dir="/path/to/source/directory"
backup_file="$backup_dir/backup_$(date +%Y-%m-%d_%H%M%S).tar.gz"

tar -czvf $backup_file $source_dir

You can execute this script periodically to create regular backups. But manually executing the script can be tedious, especially if you need to create backups frequently. That's where cron comes in.

Task 3: Automating Backups with Cron

Cron is a tool for scheduling tasks in Linux. We can use it to automate the backup script we created in Task 2. To create a cron job, we need to edit the crontab file using the crontab command.

Here's an example crontab entry:

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

This cron job will execute the backup script every day at midnight. The five asterisks represent the schedule parameters: minute (0-59), hour (0-23), day of the month (1-31), month (1-12), and day of the week (0-6, where 0 is Sunday).

Task 4: User Management

The final task is to create two users in Linux and display their usernames. User management is important in Linux to control access to resources and ensure security. We can use the useradd command to create users and the cut command to display their usernames.

Here's the script:

#!/bin/bash

user1="john"
user2="jane"

useradd $user1
useradd $user2

cut -d: -f1 /etc/passwd | grep $user1
cut -d: -f1 /etc/passwd | grep $user2

This script creates two users named "john" and "jane", and displays their usernames. You can modify this script to add more users or change their properties.

Happy Learning ๐Ÿ˜„

Bhaktiben Kadiya

ย