Advanced Shell Scripting

Advanced Shell Scripting

Day 5

This is the advanced shell scripting or not the beginner level at least.

Using either Loops or commands with start day and end day variables using arguments create a dir in the current directory.

======file name is - count.sh==========
#!/bin/bash
for i in $(seq $1 $2)
do
  mkdir day$i
done
=============================
How to execute it?
$ sh <filename.sh> <parameter1> <parameter2>
$ sh count.sh 1 90

Here $1 is the first giver parameter and $2 is a second given parameter.

Create a Script to backup all your work done till now

#!/bin/bash

#to create a backup tar -cvzf <file name> <location of files/dirs to be backed up>
tar -czvf work_backup.tar.gz /home/ubuntu/workdir


#to view inside the tar file
tar -tf work_backup.tar.gz

#to extract the tar in pwd
tar -xf work_backup.tar.gz

#to extract particular content from the tar file
tar xzvf work_backup.tar.gz <filename/dir from tar file>

#to extract the content to specific dir
tar -xzf work_backup.tar.gz -C /home/ubuntu/extracted/

About Cron and Crontab, to automate the backup Script

In Linux, cron is a time-based job scheduler. It is a utility that allows you to schedule and automate the execution of tasks or commands at specific intervals or at predefined times. These tasks can be scripts, programs, or any command that you want to run automatically.

Cron uses a configuration file called crontab (short for cron table) to manage the scheduling of tasks. Each user on a Linux system can have their own crontab file, which contains a list of commands or scripts to be executed and the schedule at which they should run.

The crontab file consists of lines that represent individual cron jobs. Each line follows a specific format, indicating the schedule and the command to be executed. The schedule is defined using a combination of time and date fields, specifying when the command should run.

Here is the basic structure of a cron job entry in the crontab file:

* * * * * command

The asterisks (*) represent different time and date fields:

  • Minute (0-59)

  • Hour (0-23)

  • Day of the month (1-31)

  • Month (1-12)

  • Day of the week (0-6, where Sunday is 0 or 7)

You can replace the asterisks with specific values or use special characters to define schedules. For example, to run a command every day at 2:30 PM, you would use:

30 14 * * * command

To edit the crontab file for a specific user, you can use the crontab command followed by the -e option and the username. This will open the crontab file in the default text editor, allowing you to add, modify, or remove cron job entries.

Cronjob operations-

#To list the cronjobs already set up 

$crontab -l

#To edit the add the cronjob,

$crontab -e

#To remove all the cronjobs,

$crontab -r

Cron is a powerful tool for automating repetitive tasks on a Linux system. It is commonly used for tasks such as system maintenance, data backups, log rotation, and periodic updates.