Tools: Day 5 β€” Bash Scripting for Automation (2026)

Tools: Day 5 β€” Bash Scripting for Automation (2026)

🧠 Understanding Linux Shells & Package Managers

🐚 Popular Linux Shells

πŸ“¦ Linux Package Managers

πŸš€ What is Bash?

🧠 What is Bash Scripting?

⚑ Why Bash Automation Matters

πŸ“‚ Bash Script Structure

πŸ”₯ Variables in Bash

βœ… Creating Variables

⚠️ Important Rule

🧾 User Input

πŸ“Œ Command Line Arguments

πŸ” Conditional Statements

βœ… If Statement

βœ… If-Else

βœ… If-Elif-Else

🧠 Comparison Operators

πŸ” Loops in Bash

βœ… For Loop

βœ… Range Loop

βœ… While Loop

βœ… Infinite Loop

πŸ”¨ Functions in Bash

πŸ“¦ Arrays in Bash

πŸ“ File Operations

βœ… Check if File Exists

βœ… Create File

βœ… Append to File

βš™οΈ Process Automation

βœ… Kill Process

βœ… Restart Service

βœ… Check Service Status

πŸ•’ Cron Jobs for Scheduling

βœ… Run Every Day at Midnight

βœ… Run Every 5 Minutes

πŸš€ Real-World Automation Scripts

πŸ”₯ 1️⃣ Automated Backup Script

πŸ”₯ 2️⃣ Disk Usage Monitoring Script

πŸ”₯ 3️⃣ Website Monitoring Script

πŸ”₯ 4️⃣ Auto Deployment Script

πŸ”₯ 5️⃣ Log Cleanup Script

πŸ›‘οΈ Error Handling in Bash

πŸ“Œ Exit Codes

πŸ§ͺ Debugging Bash Scripts

βœ… Run in Debug Mode

βœ… Strict Mode (Highly Recommended)

⚑ Bash Automation in DevOps

πŸ” Security Best Practices

❌ Avoid Hardcoding Passwords

βœ… Quote Variables

βœ… Validate Inputs

πŸ“š Important Bash Commands Every Engineer Should Know

πŸš€ Bash vs Python for Automation

🎯 Best Practices for Bash Scripting

🧠 Final Thoughts Modern infrastructure runs on automation. You will eventually write Bash scripts. From automating backups to deploying servers, monitoring systems, managing logs, and running CI/CD pipelines β€” Bash is everywhere. If Linux is the operating system of the internet, then Bash is its automation language. GitHub Repo:

https://github.com/17J/30-Days-Cloud-DevSecOps-Journey Command Sheet:https://bash-command-sheets-k51c.vercel.app/ Linux Cron Job Scheduler:https://crontab.guru/ many beginners get confused between: So before learning Bash scripting, let’s first understand the Linux shell ecosystem. Linux has multiple shells. A shell is simply a command interpreter that lets users communicate with the operating system. Package managers install software. Different Linux distributions use different package managers. It is the default shell for most Linux distributions. A shell is simply a program that allows users to interact with the operating system. These commands are executed through the shell. A Bash script is a file containing Linux commands executed sequentially. Instead of manually typing commands repeatedly, you automate them inside a script. ❌ Manual server setup❌ Repetitive deployments❌ Manual backups❌ Human errors❌ Slow operations With Bash automation: βœ… Faster workflowsβœ… Repeatable processesβœ… Infrastructure consistencyβœ… Reduced human mistakesβœ… Better productivity Variables store data. Access variables using $. Take input dynamically. Arguments passed while running scripts. Conditions allow decision-making. Loops repeat tasks automatically. Functions help organize reusable code. Cron automates scripts at scheduled times. βœ… Compresses filesβœ… Creates timestamp backupβœ… Automates backup process Deletes logs older than 7 days. Always validate failures. $? stores previous command status. Shows command execution step-by-step. Bash is heavily used in: Never write insecure scripts. Always sanitize user input. Most DevOps engineers use both. βœ… Use meaningful variable namesβœ… Add commentsβœ… Use functionsβœ… Handle errors properlyβœ… Use strict modeβœ… Keep scripts modularβœ… Log important actions

βœ… Test before production Bash scripting is one of the most valuable skills in Linux, DevOps, Cloud, and Cybersecurity. The engineers who automate repetitive tasks become exponentially more productive. Over time, Bash becomes your operational superpower. Templates let you quickly answer FAQs or store snippets for re-use. Hide child comments as well For further actions, you may consider blocking this person and/or reporting abuse

Code Block

Copy

User β†’ Shell β†’ Linux Kernel β†’ Hardware User β†’ Shell β†’ Linux Kernel β†’ Hardware User β†’ Shell β†’ Linux Kernel β†’ Hardware pwd ls mkdir project pwd ls mkdir project pwd ls mkdir project #!/bin/bash echo "Hello Rahul" date uptime #!/bin/bash echo "Hello Rahul" date uptime #!/bin/bash echo "Hello Rahul" date uptime chmod +x hello.sh chmod +x hello.sh chmod +x hello.sh #!/bin/bash # Comments start with # echo "Starting Script" # Commands here #!/bin/bash # Comments start with # echo "Starting Script" # Commands here #!/bin/bash # Comments start with # echo "Starting Script" # Commands here name="Rahul" age=22 city="Delhi" name="Rahul" age=22 city="Delhi" name="Rahul" age=22 city="Delhi" echo $name echo $age echo $name echo $age echo $name echo $age name = "Rahul" name = "Rahul" name = "Rahul" name="Rahul" name="Rahul" name="Rahul" #!/bin/bash echo "Enter your name:" read name echo "Welcome $name" #!/bin/bash echo "Enter your name:" read name echo "Welcome $name" #!/bin/bash echo "Enter your name:" read name echo "Welcome $name" #!/bin/bash echo "First argument: $1" echo "Second argument: $2" #!/bin/bash echo "First argument: $1" echo "Second argument: $2" #!/bin/bash echo "First argument: $1" echo "Second argument: $2" ./script.sh Rahul Linux ./script.sh Rahul Linux ./script.sh Rahul Linux First argument: Rahul Second argument: Linux First argument: Rahul Second argument: Linux First argument: Rahul Second argument: Linux #!/bin/bash age=20 if [ $age -ge 18 ] then echo "Adult" fi #!/bin/bash age=20 if [ $age -ge 18 ] then echo "Adult" fi #!/bin/bash age=20 if [ $age -ge 18 ] then echo "Adult" fi #!/bin/bash num=5 if [ $num -gt 10 ] then echo "Greater than 10" else echo "Less than or equal to 10" fi #!/bin/bash num=5 if [ $num -gt 10 ] then echo "Greater than 10" else echo "Less than or equal to 10" fi #!/bin/bash num=5 if [ $num -gt 10 ] then echo "Greater than 10" else echo "Less than or equal to 10" fi #!/bin/bash marks=75 if [ $marks -ge 90 ] then echo "Grade A" elif [ $marks -ge 70 ] then echo "Grade B" else echo "Grade C" fi #!/bin/bash marks=75 if [ $marks -ge 90 ] then echo "Grade A" elif [ $marks -ge 70 ] then echo "Grade B" else echo "Grade C" fi #!/bin/bash marks=75 if [ $marks -ge 90 ] then echo "Grade A" elif [ $marks -ge 70 ] then echo "Grade B" else echo "Grade C" fi #!/bin/bash for i in 1 2 3 4 5 do echo "Number: $i" done #!/bin/bash for i in 1 2 3 4 5 do echo "Number: $i" done #!/bin/bash for i in 1 2 3 4 5 do echo "Number: $i" done for i in {1..10} do echo $i done for i in {1..10} do echo $i done for i in {1..10} do echo $i done #!/bin/bash count=1 while [ $count -le 5 ] do echo $count ((count++)) done #!/bin/bash count=1 while [ $count -le 5 ] do echo $count ((count++)) done #!/bin/bash count=1 while [ $count -le 5 ] do echo $count ((count++)) done while true do echo "Running..." sleep 2 done while true do echo "Running..." sleep 2 done while true do echo "Running..." sleep 2 done #!/bin/bash greet() { echo "Hello $1" } greet Rahul #!/bin/bash greet() { echo "Hello $1" } greet Rahul #!/bin/bash greet() { echo "Hello $1" } greet Rahul #!/bin/bash fruits=("apple" "banana" "mango") echo ${fruits[0]} echo ${fruits[1]} #!/bin/bash fruits=("apple" "banana" "mango") echo ${fruits[0]} echo ${fruits[1]} #!/bin/bash fruits=("apple" "banana" "mango") echo ${fruits[0]} echo ${fruits[1]} for fruit in "${fruits[@]}" do echo $fruit done for fruit in "${fruits[@]}" do echo $fruit done for fruit in "${fruits[@]}" do echo $fruit done #!/bin/bash if [ -f test.txt ] then echo "File exists" else echo "File not found" fi #!/bin/bash if [ -f test.txt ] then echo "File exists" else echo "File not found" fi #!/bin/bash if [ -f test.txt ] then echo "File exists" else echo "File not found" fi touch file.txt touch file.txt touch file.txt echo "New Log Entry" >> logs.txt echo "New Log Entry" >> logs.txt echo "New Log Entry" >> logs.txt pkill nginx pkill nginx pkill nginx systemctl restart nginx systemctl restart nginx systemctl restart nginx systemctl status docker systemctl status docker systemctl status docker 0 0 * * * /home/ubuntu/backup.sh 0 0 * * * /home/ubuntu/backup.sh 0 0 * * * /home/ubuntu/backup.sh */5 * * * * /home/ubuntu/monitor.sh */5 * * * * /home/ubuntu/monitor.sh */5 * * * * /home/ubuntu/monitor.sh #!/bin/bash SOURCE="/home/ubuntu/data" DEST="/backup" DATE=$(date +%Y-%m-%d) tar -czf $DEST/backup-$DATE.tar.gz $SOURCE echo "Backup completed" #!/bin/bash SOURCE="/home/ubuntu/data" DEST="/backup" DATE=$(date +%Y-%m-%d) tar -czf $DEST/backup-$DATE.tar.gz $SOURCE echo "Backup completed" #!/bin/bash SOURCE="/home/ubuntu/data" DEST="/backup" DATE=$(date +%Y-%m-%d) tar -czf $DEST/backup-$DATE.tar.gz $SOURCE echo "Backup completed" #!/bin/bash THRESHOLD=80 USAGE=$(df / | grep / | awk '{ print $5 }' | sed 's/%//g') if [ $USAGE -gt $THRESHOLD ] then echo "Disk usage exceeded threshold!" else echo "Disk usage normal" fi #!/bin/bash THRESHOLD=80 USAGE=$(df / | grep / | awk '{ print $5 }' | sed 's/%//g') if [ $USAGE -gt $THRESHOLD ] then echo "Disk usage exceeded threshold!" else echo "Disk usage normal" fi #!/bin/bash THRESHOLD=80 USAGE=$(df / | grep / | awk '{ print $5 }' | sed 's/%//g') if [ $USAGE -gt $THRESHOLD ] then echo "Disk usage exceeded threshold!" else echo "Disk usage normal" fi #!/bin/bash URL="https://example.com" STATUS=$(curl -o /dev/null -s -w "%{http_code}" $URL) if [ $STATUS -eq 200 ] then echo "Website is UP" else echo "Website is DOWN" fi #!/bin/bash URL="https://example.com" STATUS=$(curl -o /dev/null -s -w "%{http_code}" $URL) if [ $STATUS -eq 200 ] then echo "Website is UP" else echo "Website is DOWN" fi #!/bin/bash URL="https://example.com" STATUS=$(curl -o /dev/null -s -w "%{http_code}" $URL) if [ $STATUS -eq 200 ] then echo "Website is UP" else echo "Website is DOWN" fi #!/bin/bash echo "Pulling latest code..." git pull origin main echo "Installing dependencies..." npm install echo "Restarting application..." pm2 restart app #!/bin/bash echo "Pulling latest code..." git pull origin main echo "Installing dependencies..." npm install echo "Restarting application..." pm2 restart app #!/bin/bash echo "Pulling latest code..." git pull origin main echo "Installing dependencies..." npm install echo "Restarting application..." pm2 restart app #!/bin/bash find /var/log -type f -name "*.log" -mtime +7 -delete echo "Old logs deleted" #!/bin/bash find /var/log -type f -name "*.log" -mtime +7 -delete echo "Old logs deleted" #!/bin/bash find /var/log -type f -name "*.log" -mtime +7 -delete echo "Old logs deleted" #!/bin/bash mkdir test if [ $? -eq 0 ] then echo "Directory created" else echo "Failed" fi #!/bin/bash mkdir test if [ $? -eq 0 ] then echo "Directory created" else echo "Failed" fi #!/bin/bash mkdir test if [ $? -eq 0 ] then echo "Directory created" else echo "Failed" fi bash -x script.sh bash -x script.sh bash -x script.sh #!/bin/bash set -euo pipefail #!/bin/bash set -euo pipefail #!/bin/bash set -euo pipefail password="admin123" password="admin123" password="admin123" read -s password read -s password read -s password rm -rf $dir rm -rf $dir rm -rf $dir rm -rf "$dir" rm -rf "$dir" rm -rf "$dir" - DevOps Engineer - Linux Administrator - Cloud Engineer - Cybersecurity Professional - Backend Developer - GitHub Repo: https://github.com/17J/30-Days-Cloud-DevSecOps-Journey - Command Sheet: https://bash-command-sheets-k51c.vercel.app/ - Linux Cron Job Scheduler: https://crontab.guru/ - Production systems - Production deployments - 0 = success - Non-zero = failure - Undefined variables - Failed commands - Pipeline failures - Automate backups - Monitor servers - Deploy applications - Schedule tasks