+91-7678211866  info@peppertechsolutions.com

Master Linux Scripting

Complete Guide

Linux Scripting Mastery: Complete Guide with Bash, Automation & Real-World Examples (2026)

Master Linux shell scripting from basics to advanced automation. Learn bash, variables, conditionals, loops, functions, text processing, and real-world DevOps examples. For system administrators, developers, and DevOps engineers.

📅 Updated: June 2026 ⏱ 45 min read 🏷 Bash · Shell · DevOps · Automation · Linux

💡 Linux Scripting Advantage: Master shell scripting and unlock automation superpowers. Whether you’re managing 10 servers or 1,000, scripts save hours of manual work. Learn the skills that make system administrators and DevOps engineers highly valuable.

50+ Code examples & scripts
11 Major topics covered
45 min Complete reading time
Beginner–Expert Skill levels covered

Introduction to Shell Scripting

What is a shell script? A shell script is a text file containing a sequence of commands that the Linux shell executes automatically. Instead of typing commands manually, you save them in a script and run it once — saving time and reducing errors.

Why learn shell scripting?

  • Automation: Automate repetitive tasks (backups, log cleanup, system monitoring)
  • Efficiency: Run complex operations in seconds vs hours of manual work
  • Consistency: Same script runs the same way every time (no human error)
  • Career: System admins and DevOps engineers with strong scripting skills earn more
  • DevOps: CI/CD pipelines, containerization, infrastructure automation all rely on scripts

Which shell to learn? Bash (Bourne Again Shell) is the most common and powerful. Available on Linux, macOS, and Windows (via WSL). When you see “shell script” in jobs, they almost always mean Bash.

Bash Fundamentals & Syntax

Your First Bash Script Hello World and script basics

Create a file called hello.sh:

#!/bin/bash
# This is a comment
echo “Hello, World!”

Run the script:

chmod +x hello.sh
./hello.sh
Output: Hello, World!

Key points: #!/bin/bash is the shebang — tells Linux to use Bash. chmod +x makes the file executable. Lines starting with # are comments.

Variables, Operators & Data Types

Working with Variables Store and manipulate data
#!/bin/bash
# Variable assignment (no spaces around =)
name=“Alice”
age=30
count=5

# Use variables with $
echo “Name: $name, Age: $age”

# Arithmetic
result=$((10 + 5)) # result = 15
echo “10 + 5 = $result”

# Command substitution
current_date=$(date +“%Y-%m-%d”)
echo “Today is $current_date”

Important rules:

  • No spaces around = when assigning variables
  • Use $variable or ${variable} to access variables
  • Single quotes preserve literal strings. Double quotes allow variable expansion.
  • Use $(command) for command substitution (newer syntax, preferred)

Sections 4–11 in complete article: Conditionals (if/else, case statements, test operators) • Loops (for, while, until with examples) • Functions (defining, parameters, return values) • File Operations (create, read, append, delete, check existence) • Text Processing (grep, sed, awk for powerful data manipulation) • Regular Expressions (pattern matching, advanced grep) • Advanced Topics (arrays, here documents, error handling, debugging) • Real-World Examples (backup scripts, log monitoring, system health checks) • Best Practices (error handling, code style, performance optimization)

Real-World Examples & Automation Scripts

Example 1: Automated Backup Script Daily backups to a remote server
#!/bin/bash
# Daily backup script
BACKUP_DIR=“/backups”
SOURCE_DIR=“/home/user/data”
TIMESTAMP=$(date +“%Y%m%d_%H%M%S”)
LOG_FILE=“/var/log/backup.log”

# Create backup
tar -czf “$BACKUP_DIR/backup_$TIMESTAMP.tar.gz” “$SOURCE_DIR” 2>&1 | tee -a “$LOG_FILE”

# Check if backup succeeded
if [ $? -eq 0 ]; then
  echo “Backup succeeded at $(date)” >> “$LOG_FILE”
else
  echo “Backup FAILED at $(date)” >> “$LOG_FILE”
  exit 1
fi

# Remove backups older than 30 days
find “$BACKUP_DIR” -name “backup_*.tar.gz” -mtime +30 -delete

How to use:

  • Save as backup.sh and run ./backup.sh
  • Schedule with cron: 0 2 * * * /path/to/backup.sh (runs daily at 2 AM)
  • Script creates timestamped backups, logs success/failure, and auto-deletes old backups
Example 2: System Health Check Script Monitor CPU, memory, disk, and services
#!/bin/bash
# System health monitoring
CPU_USAGE=$(top -bn1 | grep “Cpu(s)” | awk ‘{print $2}’ | cut -d’%’ -f1)
MEM_USAGE=$(free | grep Mem | awk ‘{print int($3/$2 * 100)}’)
DISK_USAGE=$(df / | awk ‘NR==2 {print $5}’ | cut -d’%’ -f1)

# Check thresholds
if (( $(echo “$CPU_USAGE > 80” | bc -l) )); then
  echo “⚠️ WARNING: CPU usage is $CPU_USAGE%”
fi

if [ “$MEM_USAGE” -gt 85 ]; then
  echo “⚠️ WARNING: Memory usage is $MEM_USAGE%”
fi

if [ “$DISK_USAGE” -gt 90 ]; then
  echo “⚠️ WARNING: Disk usage is $DISK_USAGE%”
fi

# Check critical service
if ! systemctl is-active –quiet nginx; then
  echo “❌ ERROR: Nginx service is down”
  systemctl start nginx # Auto-restart
fi

Real-world use: Schedule this script every 5 minutes with cron. It monitors system health and auto-restarts services if they fail. Add email alerts to notify admins of critical issues.

Example 3: Log Analysis & Cleanup Script Parse logs and alert on errors
#!/bin/bash
# Log analysis script
LOG_FILE=“/var/log/app.log”
ERROR_COUNT=$(grep -c “ERROR” “$LOG_FILE”)
WARN_COUNT=$(grep -c “WARN” “$LOG_FILE”)

# Extract top 10 error messages
echo “=== Top Errors ===”
grep “ERROR” “$LOG_FILE” | awk -F‘: ‘ ‘{print $NF}’ | sort | uniq -c | sort -rn | head -10

# Alert if errors exceed threshold
if [ “$ERROR_COUNT” -gt 100 ]; then
  echo “ALERT: $ERROR_COUNT errors found!” | mail -s “Log Alert” admin@example.com
fi

# Archive and compress logs older than 7 days
find /var/log -name “*.log” -mtime +7 -exec gzip {} \;

Use case: Run daily to analyze application logs, identify frequent errors, and email alerts to on-call engineers. Automatically archives old logs to save disk space.

Best Practices & Performance Optimization

✅ Scripting Best Practices
  • Always check exit codes: Use $? to verify commands succeeded before proceeding.
  • Quote variables: Use "$var" not $var to prevent word splitting and globbing.
  • Use meaningful variable names: $backup_dir not $bd.
  • Add logging: Log all actions to a file for auditing and debugging.
  • Handle errors gracefully: Use set -e to exit on error, or trap errors with custom handlers.
  • Comment complex logic: Explain why you’re doing something, not just what.
  • Test thoroughly: Test scripts on test systems before running on production.
⚡ Performance Tips
  • Minimize external commands: Bash built-ins are faster than spawning processes.
  • Use pipes efficiently: cat file | grep pattern is slower than grep pattern file.
  • Avoid loops for file processing: Use awk or sed instead of looping through lines.
  • Cache results: If a command is expensive, save the result in a variable instead of calling it repeatedly.
  • Parallel processing: For long operations, use xargs -P 4 or background jobs (&) for parallelism.

❌ Common Mistakes & How to Avoid Them

  • Hardcoding paths: Use variables for paths so scripts are portable. CONFIG_DIR="${HOME}/.config"
  • Missing error checking: Always check if critical commands succeeded before using their output.
  • Unquoted variables in loops: Can cause word splitting and unexpected behavior.
  • Using system commands for math: Bash’s $(()) arithmetic is much faster than expr or bc.
  • Not testing edge cases: Test with empty inputs, special characters, large files, and missing dependencies.

📚 Recommended Learning Path

Week 1: Variables, echo, basic commands, shebang. Week 2: Conditionals (if/else, test operators), exit codes. Week 3: Loops (for, while), control flow. Week 4: Functions, script organization, error handling. Week 5: Text processing (grep, sed, awk), regular expressions. Week 6: Advanced topics (arrays, here documents, debugging). Week 7+: Build real projects: backup scripts, deployment automation, monitoring tools. Practice, practice, practice!

Master Linux Automation

Take Your Linux Scripting to the Next Level

PepperTech’s hands-on Linux scripting training covers all these topics with real DevOps automation projects. Learn from certified Linux administrators with 15+ years of production experience. Build automation tools that professionals use.

✅ 50+ Real Scripts & Examples
✅ DevOps & Automation Focus
✅ Live Lab Environment
✅ Certification Ready

📞 Call / WhatsApp +91-7678211866
📧 Email info@peppertechsolutions.com
#LinuxScripting #Bash #ShellScripting #DevOps #Automation #SystemAdministration #Linux #Programming #Tutorial

Comments are closed