Empower Your Linux Journey: Unleash the Potential of Shell Scripting for Seamless Automation

Empower Your Linux Journey: Unleash the Potential of Shell Scripting for Seamless Automation

What is Shell

In simple terms, a shell is a command-line interface that allows a user to interact with a computer's operating system by typing commands. It's a program that takes your input (commands) and communicates with the operating system to execute those commands.When you open a terminal or command prompt, you're typically using a shell. The shell interprets the commands you type and carries out the requested actions, such as running programs, managing files, and configuring system settings.

Shell is broadly classified into two categories –

  • Command Line Shell

  • Graphical shell

Types Of Shells in Linux

Bash (Bourne Again Shell): Bash is the default shell for most Linux distributions and is widely used. It is an enhanced version of the original Bourne Shell (sh) and includes features from other shells such as the C Shell (csh) and Korn Shell (ksh). Bash is known for its flexibility and powerful scripting capabilities.

Zsh (Z Shell): Zsh is an extended version of the Bourne Shell with additional features and improvements. It includes advanced command-line editing, spelling correction, and support for themes and plugins. Zsh is known for its interactive and user-friendly features.

Fish (Friendly Interactive Shell): Fish is designed to be user-friendly and interactive. It has syntax highlighting, auto-suggestions, and an intuitive command-line interface. Fish is aimed at providing a pleasant and easy-to-use experience for both beginners and experienced users.

Ksh (Korn Shell): The Korn Shell is an older shell that influenced Bash. It provides advanced scripting features and is POSIX-compliant. While not as widely used as Bash, it is still available on many systems.

Csh (C Shell): Csh is a shell with a syntax resembling the C programming language. It includes features like command history and job control. While not as commonly used as Bash, it is still available on many systems.

What is Shell Scripting

Shell scripting involves writing a series of commands for a shell (command-line interface) to execute. It's a way to automate tasks and create simple programs using a scripting language within the shell environment.

Shell scripts often have file extensions like .sh (for Bash scripts)

Why do we need shell scripts?

  • To avoid repetitive work and automation

  • System admins use shell scripting for routine backups.

  • System monitoring

  • Adding new functionality to the shell etc.

How to Execute the script file ?

Using the ./ (dot-slash) notation:

This method is used when the script has execute permissions.

Navigate to the directory where the script is located.

Run the script using ./ followed by the script name.

Ensure execute permissions are set: chmod +x script_name.

cd /path/to/script_directory
./myscript.sh

Using the shell interpreter explicitly:

This method is used when you want to specify the shell interpreter explicitly, regardless of execute permissions.Run the script using the bash command followed by the script name.This method does not rely on the execute permissions; however, the script should be readable.

bash myscript.sh

Structure of Shell Scripting

#!/bin/bash
# Description: A simple shell script

# Variable declarations
variable1="value1"
variable2="value2"

# Main script logic
echo "Hello, World!"

# Using variables in commands
echo "Values of variables: $variable1, $variable2"

# Conditional statements
if [ "$variable1" == "value1" ]; then
    echo "Variable 1 is equal to 'value1'"
else
    echo "Variable 1 is not equal to 'value1'"
fi

# Looping construct
for i in {1..5}; do
    echo "Iteration $i"
done

# Function definition
function my_function() {
    echo "This is a function"
}

# Function invocation
my_function

# End of script

Explanation:

Shebang Line (#!/bin/bash): The shebang line at the beginning of the script tells the system which interpreter to use to execute the script. In this case, it's Bash.

Comments (#): Comments are lines prefixed with # and are ignored by the shell. They provide information about the script, including its purpose, usage, and any important notes.

Variable Declarations: You can declare variables to store values that can be used throughout the script.

Main Script Logic: This is where the main commands and logic of your script reside.

Conditional Statements (if): Conditional statements are used for decision-making. They execute different commands based on whether a certain condition is true or false.

Looping Constructs (for, while, etc.): Loops are used for repeating a set of commands multiple times.

Function Definition and Invocation: Functions allow you to group related commands together, making your script modular and easier to understand.

Remember to make your scripts readable, and use comments to explain complex sections. Also, ensure the script has the execute permission (chmod +x script_name.sh) before running it.

How to create Backup in Shell Scripting

Script :

#!/bin/bash

<< comment
this is backup script
from source to destination
comment


#function to create backup
create_backup(){

#Source Direactory
scr_dir="/home/ubuntu/scripts"

#Target Directory 
tgt_dir="/home/ubuntu/backups"

#create the tar file with timestamp
backup_filename="backup_$(date +%Y-%m-%d-%H-%M-%S).tar.gz"

echo "backup started"

echo "Backing upto : $backup_filename ...."

#now we create the all file into tar file and store them in target dir
tar -czvf "${tgt_dir}/${backup_filename}" "$scr_dir"

echo "Backup successful"
}

#invoke the function
create_backup

Cron Task in Linux :

A cron job is a scheduled task that runs at specific intervals on a Unix-like operating system, including Linux. Here's how you can set up a cron job:

  1. Open your terminal.

  2. Type crontab -e and press Enter. This command will open the crontab file in your default text editor (usually Vi or Nano).

  3. If prompted, choose your preferred text editor.

  4. In the crontab file, add a new line at the bottom to specify your cron job. The general format for a cron job entry is:

This format consists of five fields separated by spaces:

  • The first field is for minutes (0-59).

  • The second field is for hours (0-23).

  • The third field is for days of the month (1-31).

  • The fourth field is for months (1-12).

  • The fifth field is for days of the week (0-7, where 0 and 7 represent Sunday).

You can use * to indicate "every" for any field. For example, * * * * * would run the command every minute.

After specifying the timing, add the command you want to run. For example, to run a script located at /home/user/script.sh every day at 3 AM, you would add:

0 3 * * * /home/user/script.sh

Save and close the crontab file. In Vi, you can do this by pressing Esc, then typing :wq and pressing Enter. In Nano, you can do this by pressing Ctrl + O to write the file and Ctrl + X to exit.

Did you find this article valuable?

Support Shravankumar Sirvi by becoming a sponsor. Any amount is appreciated!