Friday, January 17, 2025

Linux 101: Part 7 - Shell Scripting and Automation in Linux


In this seventh part of our Linux 101 series, we will explore Shell Scripting and Automation, which helps automate repetitive tasks and improve efficiency in Linux system administration.

What is Shell Scripting?

A shell script is a file containing a series of commands that are executed by the shell. It allows users to automate tasks, schedule jobs, and simplify system management.

Why Use Shell Scripting?

  • Automates repetitive tasks.
  • Reduces manual errors.
  • Improves efficiency in system administration.
  • Schedules jobs to run at specific times.

Writing a Basic Shell Script

1. Creating a Script File

Use a text editor to create a new script file:

nano myscript.sh

2. Writing the Script

Add the following lines:

#!/bin/bash
# This is a simple script
echo "Hello, Linux World!"
date

3. Making the Script Executable

chmod +x myscript.sh

4. Running the Script

./myscript.sh

Variables in Shell Scripting

You can store values in variables and use them within the script.

#!/bin/bash
name="Linux User"
echo "Hello, $name!"

Conditional Statements

Shell scripts can use if statements for decision-making.

#!/bin/bash
num=10
if [ $num -gt 5 ]; then
    echo "Number is greater than 5"
else
    echo "Number is 5 or less"
fi

Looping in Shell Scripts

For Loop

#!/bin/bash
for i in {1..5}; do
    echo "Number: $i"
done

While Loop

#!/bin/bash
count=1
while [ $count -le 5 ]; do
    echo "Count: $count"
    count=$((count + 1))
done

Functions in Shell Scripts

Functions help structure scripts into reusable blocks.

#!/bin/bash
hello() {
    echo "Hello, Linux!"
}
hello

Scheduling Tasks with Cron Jobs

Cron jobs allow tasks to be scheduled at specific times.

Editing the Cron Table

crontab -e

Example Cron Job

Run a script every day at midnight:

0 0 * * * /path/to/script.sh

Automating System Maintenance Tasks

Examples of common automation tasks:

  • Backup important files:
    tar -czf backup.tar.gz /home/user/documents
    
  • Clean temporary files:
    rm -rf /tmp/*
    
  • Monitor system resource usage:
    free -m >> memory.log
    

Conclusion

Shell scripting and automation are powerful tools in Linux for improving productivity and system efficiency. In the next part, we will cover System Monitoring and Performance Tuning in Linux to optimize system performance.

Stay tuned for Linux 101: Part 8 – System Monitoring and Performance Tuning in Linux!

0 comments: