sse
objc
+
+
dart
+
next
rest
+
ember
+
+
rs
webstorm
+
pascal
+
preact
+
@
vb
+
+
symfony
hugging
packer
+
+
fiber
weaviate
ios
$
+
+
gitlab
+
strapi
scipy
+
aws
+
koa
lua
webpack
termux
<=
parcel
couchdb
+
prettier
+
+
+
+
+
+
d
kotlin
&&
+
+
+
[]
symfony
+
xcode
puppet
notepad++
+
gulp
+
next
+
toml
+
backbone
+
+
+
cosmos
+
+
+
+
npm
+
~
+
Back to Blog
🤖 Bash Scripting Basics for Automation in AlmaLinux: Beginner's Journey
AlmaLinux Bash Scripting

🤖 Bash Scripting Basics for Automation in AlmaLinux: Beginner's Journey

Published Aug 20, 2025

Start your bash scripting journey in AlmaLinux! Learn variables, loops, conditions, and functions to automate tasks. Perfect for beginners with fun examples and practical scripts.

11 min read
0 views
Table of Contents

🤖 Bash Scripting Basics for Automation in AlmaLinux: Beginner’s Journey

Ever felt like you’re doing the same commands over and over? 😩 Well, guess what - that’s exactly why bash scripting exists! I still remember my first script… It was just three lines, but when it worked? Man, I felt like a wizard! 🧙‍♂️ Today, I’m gonna show you how to write bash scripts that’ll automate all those boring tasks. And honestly? It’s easier than you think!

🤔 Why is Bash Scripting Important?

Let me tell you something - bash scripting changed my life. Okay, maybe that’s dramatic, but seriously, it’s THAT useful! Here’s why you need this:

  • 🤖 Automate Everything - Stop typing the same commands daily
  • Save Hours - Let scripts do the work while you drink coffee
  • 🎯 Fewer Mistakes - Scripts don’t have typos (once they work!)
  • 💪 Feel Powerful - Control your system like a boss
  • 📈 Career Boost - Every IT job loves automation skills
  • 🚀 Work Smarter - Not harder, right?

Plus, there’s something really satisfying about watching your script do in seconds what used to take minutes! 😎

🎯 What You Need

Before we start scripting (and trust me, this is gonna be fun!), let’s check you have:

  • ✅ AlmaLinux system ready to go
  • ✅ Terminal access (we’ll live here!)
  • ✅ Text editor (nano, vim, or whatever you like)
  • ✅ 20 minutes to change your life (not kidding!)
  • ✅ Willingness to make mistakes (that’s how we learn!)

📝 Step 1: Your First Bash Script

Alright, let’s write your first script! Don’t worry, we’ll start super simple.

Create Your First Script

# Create a script file
nano ~/my-first-script.sh

# Type this in the file:
#!/bin/bash
# My very first bash script!

echo "Hello from my script! 👋"
echo "Today is: $(date)"
echo "You are: $(whoami)"
echo "Your home is: $HOME"

Make It Executable

# Give execute permission
chmod +x ~/my-first-script.sh

# Run your script!
./my-first-script.sh

# You'll see:
# Hello from my script! 👋
# Today is: Mon Aug 19 15:30:45 EDT 2025
# You are: yourname
# Your home is: /home/yourname

Boom! You’re a scripter now! 🎉

Understanding the Shebang

#!/bin/bash  # This is the "shebang" - tells system to use bash

# You might also see:
#!/usr/bin/env bash  # More portable version
#!/bin/sh           # For POSIX shell (more basic)

🔧 Step 2: Variables and User Input

Variables are like containers for your data. Let’s play with them!

Basic Variables

nano ~/variables-demo.sh

#!/bin/bash
# Learning about variables

# Simple variables (no spaces around =)
name="AlmaLinux"
version=9
is_awesome=true

# Using variables (need $ to access)
echo "I'm using $name version $version"
echo "Is it awesome? $is_awesome"

# Command output in variables
current_date=$(date +%Y-%m-%d)
file_count=$(ls | wc -l)

echo "Today is: $current_date"
echo "Files in current directory: $file_count"

Getting User Input

nano ~/user-input.sh

#!/bin/bash
# Getting input from user

echo "What's your name? 🤔"
read user_name

echo "How old are you?"
read user_age

echo "Nice to meet you, $user_name!"
echo "Wow, $user_age years young! 🎂"

# Fancy input with prompt
read -p "What's your favorite color? " fav_color
echo "I love $fav_color too!"

# Secret input (for passwords)
read -s -p "Enter password: " password
echo ""  # New line after hidden input
echo "Password length: ${#password} characters"

🌟 Step 3: Conditions (If/Then/Else)

Time to make decisions in your scripts! This is where it gets interesting.

Basic If Statement

nano ~/check-disk.sh

#!/bin/bash
# Check disk space

# Get disk usage percentage
disk_usage=$(df -h / | awk 'NR==2 {print $5}' | sed 's/%//')

echo "Current disk usage: $disk_usage%"

if [ $disk_usage -gt 80 ]; then
    echo "⚠️ WARNING: Disk space is running low!"
elif [ $disk_usage -gt 60 ]; then
    echo "📊 Disk usage is moderate. Keep an eye on it."
else
    echo "✅ Plenty of disk space available!"
fi

Checking Files and Directories

nano ~/file-checker.sh

#!/bin/bash
# File and directory checker

file_to_check="$1"  # First argument passed to script

if [ -z "$file_to_check" ]; then
    echo "Usage: $0 <filename>"
    exit 1
fi

# Different file checks
if [ -e "$file_to_check" ]; then
    echo "✅ $file_to_check exists!"
    
    if [ -f "$file_to_check" ]; then
        echo "   📄 It's a regular file"
        echo "   Size: $(ls -lh "$file_to_check" | awk '{print $5}')"
    elif [ -d "$file_to_check" ]; then
        echo "   📁 It's a directory"
        echo "   Contains: $(ls "$file_to_check" | wc -l) items"
    fi
    
    if [ -r "$file_to_check" ]; then
        echo "   👀 Readable"
    fi
    if [ -w "$file_to_check" ]; then
        echo "   ✏️ Writable"
    fi
    if [ -x "$file_to_check" ]; then
        echo "   🏃 Executable"
    fi
else
    echo "❌ $file_to_check doesn't exist!"
fi

✅ Step 4: Loops - Do Things Repeatedly

Loops are where bash scripting really shines! Let’s automate repetitive tasks.

For Loops

nano ~/backup-files.sh

#!/bin/bash
# Backup important files

# Create backup directory
backup_dir="$HOME/backups/$(date +%Y%m%d)"
mkdir -p "$backup_dir"

# List of files to backup
files_to_backup=(
    "/etc/hosts"
    "/etc/resolv.conf"
    "$HOME/.bashrc"
    "$HOME/.bash_profile"
)

# Loop through and backup each file
for file in "${files_to_backup[@]}"; do
    if [ -f "$file" ]; then
        echo "📦 Backing up: $file"
        cp "$file" "$backup_dir/" 2>/dev/null && echo "   ✅ Success!" || echo "   ❌ Failed!"
    else
        echo "⚠️ Skipping $file (not found)"
    fi
done

echo "🎉 Backup complete! Files saved to: $backup_dir"

While Loops

nano ~/monitor-service.sh

#!/bin/bash
# Monitor a service

service_name="httpd"  # Change to your service
check_interval=5      # Seconds between checks
max_checks=10        # Maximum number of checks

counter=0
echo "👀 Monitoring $service_name service..."

while [ $counter -lt $max_checks ]; do
    if systemctl is-active --quiet "$service_name"; then
        echo "✅ [$counter/$max_checks] $service_name is running"
    else
        echo "❌ [$counter/$max_checks] $service_name is DOWN!"
        # Try to restart
        echo "   🔄 Attempting restart..."
        sudo systemctl start "$service_name"
    fi
    
    ((counter++))
    sleep $check_interval
done

echo "Monitoring complete after $max_checks checks"

🎮 Quick Examples

Example 1: System Info Script 💻

nano ~/system-info.sh

#!/bin/bash
# Complete system information script

echo "======================================"
echo "     🖥️ SYSTEM INFORMATION REPORT"
echo "======================================"
echo ""

# Hostname and OS
echo "📍 Hostname: $(hostname)"
echo "🐧 OS: $(cat /etc/redhat-release)"
echo "🏗️ Kernel: $(uname -r)"
echo ""

# CPU Info
echo "🧠 CPU Information:"
echo "   Model: $(lscpu | grep 'Model name' | cut -d':' -f2 | xargs)"
echo "   Cores: $(nproc)"
echo "   Load: $(uptime | awk -F'load average:' '{print $2}')"
echo ""

# Memory
echo "💾 Memory Usage:"
free -h | grep "^Mem:" | awk '{print "   Total: "$2"\n   Used: "$3"\n   Free: "$4}'
echo ""

# Disk
echo "💿 Disk Usage:"
df -h / | awk 'NR==2 {print "   Total: "$2"\n   Used: "$3"\n   Available: "$4"\n   Usage: "$5}'
echo ""

# Network
echo "🌐 Network Interfaces:"
ip -4 addr show | grep inet | grep -v 127.0.0.1 | awk '{print "   "$NF": "$2}'
echo ""

# Top processes
echo "📊 Top 5 CPU-hungry processes:"
ps aux | sort -rk 3,3 | head -6 | tail -5 | awk '{print "   "$11" ("$3"%)"}'
echo ""

echo "======================================"
echo "Report generated: $(date)"

Example 2: Automated Backup Script 📦

nano ~/smart-backup.sh

#!/bin/bash
# Smart backup script with rotation

# Configuration
SOURCE_DIR="$HOME/Documents"
BACKUP_BASE="$HOME/Backups"
MAX_BACKUPS=7  # Keep only 7 days of backups

# Create backup filename with date
BACKUP_NAME="backup-$(date +%Y%m%d-%H%M%S).tar.gz"
BACKUP_PATH="$BACKUP_BASE/$BACKUP_NAME"

# Function to clean old backups
cleanup_old_backups() {
    echo "🧹 Cleaning old backups..."
    cd "$BACKUP_BASE"
    ls -t backup-*.tar.gz 2>/dev/null | tail -n +$((MAX_BACKUPS + 1)) | xargs -r rm -v
}

# Main backup process
echo "🚀 Starting backup process..."
echo "   Source: $SOURCE_DIR"
echo "   Destination: $BACKUP_PATH"

# Create backup directory if needed
mkdir -p "$BACKUP_BASE"

# Check if source exists
if [ ! -d "$SOURCE_DIR" ]; then
    echo "❌ Error: Source directory doesn't exist!"
    exit 1
fi

# Create the backup
echo "📦 Creating backup..."
tar -czf "$BACKUP_PATH" -C "$(dirname "$SOURCE_DIR")" "$(basename "$SOURCE_DIR")" 2>/dev/null

if [ $? -eq 0 ]; then
    SIZE=$(ls -lh "$BACKUP_PATH" | awk '{print $5}')
    echo "✅ Backup created successfully! Size: $SIZE"
    
    # Clean old backups
    cleanup_old_backups
    
    # Show current backups
    echo "📋 Current backups:"
    ls -lh "$BACKUP_BASE"/backup-*.tar.gz | tail -5
else
    echo "❌ Backup failed!"
    exit 1
fi

Example 3: User Management Script 👥

nano ~/user-manager.sh

#!/bin/bash
# Interactive user management script

show_menu() {
    echo ""
    echo "========================================="
    echo "     👥 USER MANAGEMENT MENU"
    echo "========================================="
    echo "1) 📋 List all users"
    echo "2) ➕ Create new user"
    echo "3) 🔐 Change user password"
    echo "4) 👀 Show user info"
    echo "5) ❌ Delete user"
    echo "6) 🚪 Exit"
    echo "========================================="
}

# Function to list users
list_users() {
    echo "📋 System users (UID >= 1000):"
    awk -F: '$3 >= 1000 {print "   👤 " $1 " (UID: " $3 ")"}' /etc/passwd
}

# Function to create user
create_user() {
    read -p "Enter username: " username
    
    if id "$username" &>/dev/null; then
        echo "❌ User $username already exists!"
    else
        sudo useradd -m "$username"
        echo "✅ User $username created!"
        read -p "Set password now? (y/n): " setpass
        if [[ $setpass == "y" ]]; then
            sudo passwd "$username"
        fi
    fi
}

# Main loop
while true; do
    show_menu
    read -p "Choose option (1-6): " choice
    
    case $choice in
        1) list_users ;;
        2) create_user ;;
        3) 
            read -p "Username: " username
            sudo passwd "$username"
            ;;
        4)
            read -p "Username: " username
            id "$username" 2>/dev/null || echo "User not found!"
            ;;
        5)
            read -p "Username to delete: " username
            read -p "Are you sure? (yes/no): " confirm
            if [[ $confirm == "yes" ]]; then
                sudo userdel -r "$username" 2>/dev/null && echo "✅ Deleted!" || echo "❌ Failed!"
            fi
            ;;
        6) 
            echo "👋 Goodbye!"
            exit 0
            ;;
        *)
            echo "❌ Invalid option!"
            ;;
    esac
done

🚨 Fix Common Problems

Problem 1: “Permission denied” ❌

Your script won’t run?

# Check permissions
ls -l script.sh

# Fix it!
chmod +x script.sh

# Or run with bash directly
bash script.sh

Problem 2: “Command not found” ❌

Script can’t find commands?

# Add full paths in script
/usr/bin/echo "Hello"  # Instead of just 'echo'

# Or set PATH at script beginning
#!/bin/bash
PATH=/usr/bin:/bin:/usr/sbin:/sbin:$PATH

Problem 3: Variables Not Working ❌

Variables acting weird? Here’s why:

# WRONG - spaces around =
name = "John"  # This won't work!

# RIGHT - no spaces
name="John"

# WRONG - no $ when accessing
echo name  # Prints "name"

# RIGHT - use $
echo $name  # Prints "John"
echo ${name}  # Also works, better for complex cases

Problem 4: Script Hangs Forever ❌

# Add timeout to commands
timeout 5 ping google.com

# Add counter to loops
max_attempts=10
counter=0
while [ $counter -lt $max_attempts ]; do
    # Your code here
    ((counter++))
done

# Always have exit condition!

📋 Simple Commands Summary

TaskCommand
🏃 Run script./script.sh or bash script.sh
✏️ Make executablechmod +x script.sh
🐛 Debug modebash -x script.sh
📝 Check syntaxbash -n script.sh
📊 Script locationwhich scriptname
🔍 Find scriptsfind ~ -name "*.sh"
📖 View scriptcat script.sh

💡 Tips for Success

  1. Start Small 🐣 - Don’t try to automate everything at once
  2. Test Often 🧪 - Run your script after each change
  3. Use Comments 📝 - Future you will thank present you!
  4. Error Handling 🛡️ - Always check if commands succeeded
  5. Backup First 💾 - Before your script changes files
  6. Debug Mode 🐛 - Use bash -x to see what’s happening

Honestly? My first scripts were terrible. But you know what? They worked! And that’s all that matters when you’re learning. 😊

🏆 What You Learned

Holy cow, look what you can do now:

  • ✅ Write and run bash scripts
  • ✅ Use variables and get user input
  • ✅ Make decisions with if/then/else
  • ✅ Create loops for repetitive tasks
  • ✅ Build real automation scripts
  • ✅ Debug when things go wrong
  • ✅ Create interactive menus

🎯 Why This Matters

Here’s the thing - bash scripting literally changes how you work:

  • 🚀 Automate boring daily tasks
  • ⏰ Schedule scripts with cron for total automation
  • 💼 Essential skill for any Linux job
  • 🧠 Think like a programmer
  • 💰 Save hours every week
  • 😎 Impress everyone with your automation skills

You know what happened last month? I wrote a script that automated our backup process. What used to take an hour every Friday now runs automatically at 2 AM. My manager thinks I’m some kind of wizard! 🧙‍♂️ And honestly? You can do this too!

Remember: Every expert scripter started with “Hello World”. Keep practicing, keep experimenting, and don’t be afraid to break things (in a test environment!). You’re on your way to becoming an automation master! 🌟

Happy scripting! May your scripts run flawlessly and your automation dreams come true! 🤖🚀