Shell Scripting For DevOps Engineer

Shell Scripting For DevOps Engineer

1. Basics of Shell Scripting

Common Shells:

  • Bash (Bourne Again Shell) – Most commonly used

  • Zsh (Z Shell) – More advanced features

  • Sh (Bourne Shell) – Lightweight and minimal

Basic Syntax:

bashCopy#!/bin/bash  # Shebang line specifying the shell
echo "Hello, DevOps!"

Variables:

bashCopyname="DevOps Engineer"
echo "Welcome, $name"

User Input:

bashCopyread -p "Enter your name: " user
echo "Hello, $user!"

Conditional Statements:

bashCopyif [ -f "/etc/passwd" ]; then
  echo "File exists"
else
  echo "File not found"
fi

Loops:

bashCopyfor i in {1..5}; do
  echo "Iteration $i"
done

Functions:

bashCopygreet() {
  echo "Hello, $1"
}
greet "DevOps Engineer"

2. DevOps Use Cases for Shell Scripting

1. Automation Tasks

System Updates

bashCopy#!/bin/bash
sudo apt update && sudo apt upgrade -y

Creating Users

bashCopy#!/bin/bash
read -p "Enter username: " user
sudo useradd -m $user
echo "User $user created!"

2. Infrastructure Management

Checking Disk Space

bashCopydf -h | grep "/dev/sda1"

Monitoring CPU Usage

bashCopytop -b -n1 | grep "Cpu(s)"

Log Rotation

bashCopyfind /var/log -name "*.log" -mtime +7 -exec rm {} \;

3. CI/CD Pipeline Automation

Build & Deploy with Git Hooks

bashCopy#!/bin/bash
git pull origin main
docker-compose up -d --build

4. Kubernetes & Docker Automation

Restart Pods

bashCopykubectl delete pod --all -n your-namespace

Prune Unused Docker Resources

bashCopydocker system prune -af

3. Advanced Shell Scripting Techniques

1. Background Processes

bashCopy./long_running_script.sh &

2. Error Handling

bashCopy#!/bin/bash
set -e  # Stop script on error
mkdir /tmp/test_dir || { echo "Failed to create directory"; exit 1; }

3. Logging

bashCopyLOGFILE="/var/log/myscript.log"
echo "$(date): Script started" >> $LOGFILE

4. Secure Credential Management

bashCopyread -sp "Enter password: " password
echo "Password received."

4. Real-World DevOps Shell Script Example

Automating AWS EC2 Instance Creation

bashCopy#!/bin/bash

AMI_ID="ami-0abcdef1234567890"
INSTANCE_TYPE="t2.micro"
KEY_NAME="my-key"
SECURITY_GROUP="sg-123456"

aws ec2 run-instances --image-id $AMI_ID --instance-type $INSTANCE_TYPE \
--key-name $KEY_NAME --security-group-ids $SECURITY_GROUP