Day 5: Advanced Linux Shell Scripting for DevOps Engineers with User management

Day 5: Advanced Linux Shell Scripting for DevOps Engineers with User management

Table of contents

No heading

No headings in the article.

  1. Write a bash script create directories. sh that when the script is executed with three given arguments (one is the directory name and second is the start number of directories and third is the end number of directories ) it creates a specified number of directories with a dynamic directory name.
#!/bin/bash

if [ $# -le 2 ]
  then
      echo "Usage:$0 <directory_name>,<Start_num>,<end_num>"
      exit 1
fi

dir_name=$1
start_no=$2
end_no=$3

for ((i=$start_no; i<=$end_no; i++))
    do
    dir="$dir_name$i"
    mkdir -p $dir
    echo "Created directory succefully"
done


echo "Finished creating directories"
  1. Create a Script to backup all your work done till now.
#!/bin/bash

src_dir='/home/ubuntu/scripts'
backup_dir='/home/ubuntu/backup'

backup_name='backup_$(date %y-%m-%d %H-%m-%s).tar.gz).tar.gz'

# check if directory exist or not

if [ ! -d "$backup_dir" ]
   then
     mkdir -p "$backup_dir"
fi

tar -cvzf "$backup_dir/$backup_name" "$src_dir"

if [ $? -eq 0 ]
   then
     echo "Backup Successful"
   else
     echo "Backup Unsuccesseful"
fi
  1. What is cron and crontab?

cron is a time-based job scheduler in Linux and Unix-like operating systems. It runs in the background and is responsible for scheduling tasks or jobs (also called "cron jobs") to run at specific times and intervals.

crontab is the configuration file used to specify the cron jobs to be run. The name "crontab" comes from the combination of "cron" (the scheduler) and "table" (the configuration file).

The crontab file is a simple text file that contains a list of commands meant to be run at specified times. Each line of the crontab file represents a single cron job, and has six fields separated by spaces or tabs. These fields specify the minute, hour, day of the month, month, day of the week, and the command to be run.

# m h dom mon dow command
0 0 * * * /path/to/command

In this example, the first field specifies that the command should be run when the minute is 0, the second field specifies that the command should be run when the hour is 0 (midnight), and the remaining fields are set to *, meaning the command should be run every day of the month, every month of the year, and every day of the week.

To edit the crontab file, you can use the command crontab -e. This will open the file in the default text editor for your system, allowing you to add, edit, or remove cron jobs as needed.

  1. Create 2 users and just display their Usernames

sudo adduser user :-This will create the new user

sudo passwd user :- It will ask you to enter the password

cut -d: -f1 /etc/passwd :- It will display the usernames in your system.