SHELL SCRIPT

A shell script uses the Linux commands to perform a particular task. It provides loop and conditional control structures that repeat Linux commands or make decisions on which commands you want to execute. It will be very easy to learn if you already have some experience in programming (a very basic level will also work fine).

Shell Scripting provides automation, makes repetitive task, system monitoring easier to perform. It’s easier to get started with it. System admins use shell scripting for routine backups and various other tasks.
The shebang is followed by the path to the shell that should interpret the script.

How to write shell script ?
You can write shell scripts using text editors. On your Linux system, open a text editor program, open a new file to begin typing a shell script or shell programming, then give the shell permission to execute your shell script .
Let us understand the steps in creating a Shell Script:
  1. Create a file using a vi editor(or any other editor).
  2. Name the file with the extension .sh
  3. Start the script with #! /bin/sh (She-bang).
  4. Write some code .
  5. Save the script file.
  6. Make the script executable with command chmod +x < fileName>.sh
  7. For executing the script type bash < fileName>.sh or ./< fileName>.sh
    #!/bin/bash --- script with the shell path 
Three methods in script :
  • static method
  • dynamic method
  • argument passing method

  • Static method :
        a=10
        b=20
        c=`expr $a + $b`
        echo "the result is : $c"
        The result is :  30
    
    Echo is a print statement in shell script
    ` ` -- name of the symbol is backtick, use to write a linux commends in shell script
    Passing the variable arguments inside the script, note: we never use static method

    Dynamic method :
        echo "enter a number:"
        read a
        echo "enter a number:"
        read b
        c=`expr $a + $b`
        echo "the result is $c"
        enter a number:
        62
        enter a number:
        78
        the result is 140
        passing the variable value outside the script using read a and read b
    

    Argument passing method :
        c=`expr $1 + $2`
        echo "the result is $c"
        echo "file name :$0"
        echo "first argument :$1"
        echo "second argument :$2"
        echo "number of arguments :$#"
        echo "Arguments are :$*"
        echo "Arguments are :$@"
        echo "last command states :$?"
        echo "process id :$$
        the result is 80
        file name :./third.sh
        first argument :50
        second argument :30
        number of arguments :4
        Arguments are :50 30 20 10
        Arguments are :50 30 20 10
        last command states :0
        process id :5603
    
    When you execute a shell script, you can pass arguments to it from the command line. Inside the script, these arguments are automatically assigned to the positional parameters $1, $2, $3, etc., in the order they are provided.
    The variable $0 is the name of the script itself. The special variable $# contains the number of arguments passed to the script, and $@ contains all arguments as separate words.

    Relational operates :
    In shell scripting, relational operators are used to compare values, usually within conditional expressions. These comparisons are a fundamental part of decision-making in scripts, allowing you to branch execution flow based on the relationship between values. The most common relational operators are:
  • -eq : equals
  • -ne : not equals
  • -lt : less than
  • -le : less than or equal to
  • -gt : greater than
  • -ge : greater than or equal to
  • These operators are primarily used with numeric comparisons. For string comparisons, operators like = (or == in some shells) and != are used.
    Example :
        if [ $1 -gt $2 ]
        then
        echo "$1 is greater"
    
        num1=5 
        num2=10 
        if (( num1 < num2 )); 
        then 
        echo "$num1 is less than $num2" 
        fi
    
    Logical operator :
    In shell scripting, logical operators are used to combine or modify the logic of conditional expressions. The common logical operators include:
  • && (AND): This operator evaluates to true if both conditions on its left and right sides are true.
  • || (OR): This operator evaluates to true if either of the conditions on its left or right sides is true.
  • ! (NOT): This operator negates the condition that follows it, i.e.,if the condition after ! is true,it becomes false, and vice versa.
  • These logical operators are typically used within conditional statements like if, while, or until to control the flow of execution based on certain conditions.
        num1=5
        num2=10
    
    1. Logical AND (&&) :
        if (( num1 < 10 )) && (( num2 > 5 )); then
            echo "Both conditions are true"
        fi
    
    2. Logical OR (||) :
        if (( num1 < 10 )) || (( num2 < 5 )); then
            echo "At least one condition is true"
        fi
    
    3. Logical NOT (!)
        if ! (( num1 > 10 )); then
            echo "num1 is not greater than 10"
        fi
    
    For Loop :
    In shell scripting, the for loop is used to iterate over a list of items. It's a fundamental construct for repeating a set of commands for each item in a list. The syntax for the for loop in shell scripts is quite flexible.
    for variable in list
        do
            # Commands to execute for each item in the list
        done
    
    Example :
        for i in $(seq 1 5)
        do
            echo "Number: $i"
        done
    
    While Loop :
    A while loop in a shell script is a control flow statement that allows code to be executed repeatedly based on a given condition. This loop will continue to execute as long as the condition evaluates to true. When the condition becomes false, the loop terminates.
        while [ condition ]
        do
        # Commands to execute
        done
        Example:
        count=1
        while [ $count -le 5 ]
        do
        echo "Count: $count"
        count=$((count + 1))
        done
    
    In this script :
  • The loop will start with count = 1.
  • The condition checks if count is less than or equal to 5.
  • It prints the count and then increments it by 1.
  • Once count exceeds 5, the condition [ $count -le 5 ] evaluates to false, and the loop ends.

  • Case :
    The case statement in shell scripting is a control flow mechanism that allows you to execute different parts of your script based on matching a specific pattern against a given value.
    It's similar to the switch statement found in many other programming languages. The case statement simplifies complex conditional statements, especially when you have multiple different conditions to check.
        echo "Select the operation you want to perform:"
        echo "1) IP Address of the Hostname"
        echo "2) Currently Logged User"
        echo "3) Disk Space Usage"
    
        read  choice
    
        case $choice in
        1)hostname -i;;
        2)logname;;
        3)df -h;;
        *)echo "Invalid choice. Please select 1, 2, or 3”
        esac
    
  • If the user enters 1, the script executes hostname -i to display the IP address of the hostname.
  • If the user enters 2, the script executes logname to show the name of the currently logged user.
  • If the user enters 3, the script executes df -h to display disk space usage in a human-readable format.
  • If the user enters anything else, the script prints an error message indicating an invalid choice.
  • This structure makes it straightforward to extend the script with additional options if needed, by adding more patterns to the case statement.

    Alert log monitoring :
    Creating a shell script that monitors disk space and generates an alert if the usage exceeds a certain threshold is a practical way to manage system resources effectively. Below is a simple script that uses df -h to check the disk space usage of all mounted file systems and prints an alert if the usage exceeds a specified threshold.
        for i in `df -h|awk '{print$5}'|grep -vi 'use%'|tr -d '%'`
        do
        if [ $i -gt 80 ]
        then
            echo "`df -h|grep $i%|awk '{print$1}'` Running out of space and greater than 80%"
        fi
        done 
    


    (Log rotate)