Bash Scripting Essentials: Automate Your Linux Tasks

Introduction

Bash scripting is a powerful way to automate repetitive tasks in Linux. This tutorial covers essential bash scripting concepts, from basic syntax to advanced automation techniques.

Getting Started with Bash

Your First Script

#!/bin/bash
echo "Hello, World!"
echo "Welcome to Bash scripting!"

Making Scripts Executable

chmod +x myscript.sh
./myscript.sh

Variables and User Input

#!/bin/bash
# Variables
name="John"
age=25

# User input
echo "Enter your name:"
read user_name
echo "Hello, $user_name!"

# Command substitution
current_date=$(date)
echo "Today is: $current_date"

Conditional Statements

#!/bin/bash
echo "Enter a number:"
read number

if [ $number -gt 10 ]; then
    echo "Number is greater than 10"
elif [ $number -eq 10 ]; then
    echo "Number is equal to 10"
else
    echo "Number is less than 10"
fi

Loops and Functions

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

# Function
backup_files() {
    echo "Backing up files..."
    tar -czf backup_$(date +%Y%m%d).tar.gz /home/user/documents
    echo "Backup completed!"
}

backup_files

File Operations

#!/bin/bash
# Check if file exists
if [ -f "/etc/passwd" ]; then
    echo "File exists"
    wc -l /etc/passwd
fi

# Process all .txt files
for file in *.txt; do
    if [ -f "$file" ]; then
        echo "Processing: $file"
        # Your processing commands here
    fi
done

System Monitoring Script

#!/bin/bash
# System monitoring script
echo "=== System Monitor ==="
echo "Date: $(date)"
echo "Uptime: $(uptime)"
echo "Disk Usage:"
df -h | grep -E "^/dev"
echo "Memory Usage:"
free -h
echo "Top 5 CPU processes:"
ps aux --sort=-%cpu | head -6

This tutorial provides essential bash scripting knowledge for Linux automation and system administration tasks.

Add Comment