Shell Scripting: Complete Course Overview

Jul 20, 2024

Shell Scripting: Complete Course Overview

Introduction

  • Audience: Beginners with zero knowledge of Shell Scripting.
  • Course Includes: Basics to advanced, over 40 scripts, 5+ parts, real-life projects.
  • Goal: Understanding of Shell Scripting through continuous practice and real-life applications.

What is a Shell?

  • Shell: User interface for access to an operating system’s services.
  • Function: Executes commands and scripts, interacts with kernel.
  • Different Shell Types:
    • Bash (Bourne Again Shell): Most common and recommended.
    • Zsh (Z Shell): Default on macOS.

Default Shell Check

  • Command: echo $0 to check the default shell in Linux terminal.
  • Identify Installed Shells: Use cat /etc/shells to list all installed shells.
  • Switch Shells: Possible but not deeply covered.

Basic Script Creation

  • Example: Create a Hello World script.
    • Use #!/bin/bash at the start (shebang line).
    • Print command: echo "Hello World".
  • Permissions: Use chmod +x script_name to make it executable.
  • Execution: Run script with ./script_name.

Comments in Scripts

  • Single-line comments: Use # at the start of the line.
  • Multi-line comments: Use : ' your comment here ' :.

Variables in Shell Scripting

  • Definition: Variables can store information to be used in scripts.
  • Syntax: variable_name=value (No spaces around =).
  • Usage: Access the variable using $variable_name.
  • Example:
    name="Prashant"
    echo $name
    

Arrays in Shell Scripting

  • Definition: Arrays store multiple values in a single variable.
  • Syntax: array_name=(value1 value2 value3).
  • Access Elements: ${array_name[index]}.
  • Example:
    fruits=("Apple" "Banana" "Cherry")
    echo ${fruits[1]} # Outputs: Banana
    
  • Operations:
    • Get all values: ${array_name[@]}.
    • Get length: ${#array_name[@]}.
    • Get range: ${array_name[@]:start:length}.
    • Append values: array_name+=("AnotherValue").

String Operations

  • Length of a string: ${#var}.
  • Convert to uppercase: ${var^^}.
  • Convert to lowercase: ${var,,}.
  • Substring extraction: ${var:position:length}.

User Interaction in Scripts

  • Prompt for input: read variable_name.
  • Example:
    echo "Enter your name:"
    read name
    echo "Hello, $name!"
    

Arithmetic Operations

  • Syntax: $((expression)) for performing arithmetic operations.
  • Example:
    a=10
    b=20
    sum=$((a + b))
    echo $sum # Outputs: 30
    

Conditional Statements

  • If-else: Use to perform actions based on conditional tests.
  • Syntax:
    if [ condition ]; then
        # Commands
    elif [ condition ]; then
        # Commands
    else
        # Commands
    fi
    
  • Example:
    if [ $a -gt $b ]; then
        echo "$a is greater than $b"
    else
        echo "$a is not greater than $b"
    fi
    
  • Comparison Operators:
    • -eq: Equal
    • -ne: Not equal
    • -gt: Greater than
    • -ge: Greater than or equal to
    • -lt: Less than
    • -le: Less than or equal to

Logical Operators

  • AND: && or -a
  • OR: || or -o

Loops in Shell Scripting

  • For Loop:
    for var in list; do
        # Commands
    done
    
  • While Loop:
    while [ condition ]; do
        # Commands
    done
    
  • Until Loop:
    until [ condition ]; do
        # Commands
    done
    
  • Example of For Loop:
    for i in {1..5}; do
        echo "Number $i"
    done
    

Functions in Shell Scripting

  • Definition: Grouping commands together to be reused.
  • Syntax:
    function_name() {
        # Commands
    }
    
  • Calling Functions: Just use the function name.
  • Example:
    greet() {
        echo "Hello, $1"
    }
    greet "World" # Outputs: Hello, World
    
  • Arguments: Access using $1, $2, etc., within the function.
  • Return Values: Use return. Capture using $?.

Practical Projects

  • Project 1: Monitor Free RAM Space
    • Concept: Check if RAM usage crosses a threshold and alert.
    • Commands Used: free, awk, if-else structure, mail command for alert.
  • Project 2: Monitor Disk Usage and Send Email Alerts
    • Concept: Check disk usage, archive large/old files, send alerts.
    • Commands Used: df, find, tar, and mail.
  • Project 3: Archive Old Log Files
    • Concept: Compress and move old log files to an archive directory.
    • Commands Used: find, gzip, and mv.

Automation and Scheduling

  • Crontab: Schedule tasks to run at specified times.
  • Syntax:
    * * * * * command-to-execute
    | | | | |
    | | | | ----- Day of week (0 - 7) (Sunday=0 or 7)
    | | | ------- Month (1 - 12)
    | | -------- Day of month (1 - 31)
    | ---------- Hour (0 - 23)
    ------------ Minute (0 - 59)
    
  • Example: 0 5 * * * /path/to/script (Runs script daily at 5 AM).