Part 1 ยท Chapter 4

Git, Bash & Python

Version control and automation โ€” three tools that belong in every DevOps engineer's daily toolkit.

What you'll learn in this chapter

  • What Git is and why it is the foundation of all modern software development
  • The core Git workflow: init, clone, add, commit, push, pull, branch, merge
  • Branching strategies โ€” and why long-lived branches are painful
  • Bash scripting: writing automation scripts that save hours of manual work
  • Python for DevOps: parsing APIs, checking health, and automating cloud tasks

Git โ€” The World's Best Time Machine

Imagine you are writing a novel. It is a long one โ€” 400 pages. You have been working on it for months. At some point, you decide to experiment with a completely different ending. You rewrite the last 80 pages. Then you decide you preferred the original. If you do not have a backup, you are in trouble.

Now imagine a system that lets you save named checkpoints at any moment. "Chapter 3 done," "Added the villain," "Rewrote the ending โ€” take 2." You can go back to any of these checkpoints instantly. Better yet, you can create a parallel version of your story โ€” experiment wildly without ever risking the original โ€” and then merge the best parts back in. Other authors can work on their own parallel versions simultaneously, and the system intelligently combines everyone's changes.

That system is Git.

Before Git (and version control in general), developers would upload files via FTP, overwriting each other's work constantly. Someone would make a change, upload it, not realise their colleague had changed the same file an hour earlier, and that colleague's work would simply be gone. It was a chaotic way to collaborate, and it cost teams enormous amounts of wasted effort.

Git was created by Linus Torvalds โ€” the same person who created Linux โ€” in 2005, when he needed a version control system for the Linux kernel. It became the standard for software development and, by extension, for all of DevOps.

๐Ÿ“š Core Git Concepts

Repository (repo): Your project's complete time machine โ€” every file and every change ever made to them, stored in a .git folder.

Commit: A named snapshot of your project at a specific point in time. Every commit has a unique ID (a hash) and a message describing what changed.

Branch: A parallel version of your codebase. The main branch (usually called main) is the official version; feature branches are where you experiment.

Merge: Combining two branches โ€” incorporating the changes from a feature branch back into main.

Remote: A copy of your repository hosted somewhere else โ€” GitHub, GitLab, Bitbucket. Used for backup and collaboration.

Pull Request (PR): A proposal to merge your branch into another. Allows code review before changes are accepted.

Setting Up and the Daily Workflow

Git is pre-installed on most Linux systems. On macOS, it comes with Xcode Command Line Tools. On Windows, download Git for Windows. The first thing to do is tell Git who you are:

# Tell Git your name and email (do this once on each machine)
git config --global user.name "Ushahemba Shir"
git config --global user.email "you@example.com"

# Set VS Code as your default editor (optional but recommended)
git config --global core.editor "code --wait"

Starting a Project

# Start a new Git repository in the current directory
git init

# Copy (clone) an existing repository from GitHub
git clone https://github.com/username/my-project.git

# Clone into a specific folder name
git clone https://github.com/username/my-project.git my-app

The Everyday Cycle

Every working day with Git follows the same rhythm. You make changes, you check what you changed, you stage the changes you want to save, you commit them with a message, and you push to the remote so your team can see your work.

# See what's changed (this is the command you run most often)
git status

# See the exact line-by-line changes you made
git diff

# Stage a specific file for the next commit
git add src/server.js

# Stage everything in the current directory
git add .

# Create a commit with a descriptive message
git commit -m "Add user authentication endpoint"

# Push your commits to the remote (origin = GitHub/GitLab)
git push origin main

# Get the latest changes from the remote
git pull

# Fetch updates without merging (safer โ€” review before merging)
git fetch origin
๐Ÿ’ก Write Good Commit Messages

A commit message should answer the question: "Why did I make this change?" Not "what" โ€” the diff shows that. Bad: "fix bug". Better: "Fix null pointer crash when user has no profile picture". Good commit messages are a gift to your future self and your teammates. The rule of thumb: write the message as if completing the sentence "When applied, this commit will..."

Branching โ€” Working in Parallel

Branches are one of Git's superpowers. They let you work on a new feature without disturbing the stable code on main. While you build a new login system on your feature/new-auth branch, your teammate can be fixing a bug on fix/payment-timeout, and another person can be writing documentation on docs/api-reference โ€” all simultaneously, all without interfering with each other.

# See all branches (the * marks the current branch)
git branch

# Create a new branch
git branch feature/user-settings

# Switch to an existing branch
git checkout feature/user-settings

# Create AND switch to a new branch (the shortcut โ€” use this)
git checkout -b feature/user-settings

# Modern equivalent (git 2.23+)
git switch -c feature/user-settings

# Switch back to main
git checkout main

# Merge a feature branch into main
git merge feature/user-settings

# Delete a branch (after merging)
git branch -d feature/user-settings

# Push a branch to the remote
git push origin feature/user-settings

Viewing History

# See the commit history (each commit on one line)
git log --oneline

# See history with a visual branch graph
git log --oneline --graph --all

# See the full details of the last commit
git show HEAD

# See details of a specific commit by its hash
git show abc1234

# See who last changed each line of a file (very useful for blame)
git blame src/server.js

# Search commit messages for a keyword
git log --grep="authentication"

# See changes between two commits
git diff abc1234..def5678

Undoing Things

Every developer needs to know how to reverse their mistakes. Git makes this safe โ€” you can almost always undo something without losing work permanently.

# Undo changes to a file (before staging)
git checkout -- src/server.js

# Unstage a file (remove from the next commit, but keep changes)
git reset HEAD src/server.js

# Undo the last commit but keep the changes staged
git reset --soft HEAD~1

# Create a new commit that reverses a previous commit (safe for shared branches)
git revert abc1234
โš ๏ธ Never Force-Push to Main

git push --force rewrites history on the remote. If your teammates have based their work on commits you just deleted, their repositories are now out of sync in painful ways. Never force-push to main or any shared branch. On feature branches that only you use, it is sometimes acceptable โ€” but use it with intention.

Branching Strategy: How Teams Organize Their Work

Not all branching strategies are equal. The two most common are:

Gitflow uses a structured set of branches: main (production), develop (integration), feature branches, release branches, and hotfix branches. This was the dominant pattern for years and works well for teams with scheduled releases. But it creates long-lived branches that diverge significantly from main, leading to painful "merge hell" when it's time to integrate.

Trunk-Based Development is the model preferred by elite DevOps teams. Everyone commits directly to main (the "trunk") multiple times per day. Features that aren't ready are hidden using feature flags (code switches that can be toggled on or off without deployment). Branches, when used, are short-lived โ€” never longer than one or two days before being merged back in.

Trunk-based development is what makes CI/CD pipelines fast and reliable. When branches live for a day instead of a week, merge conflicts are small. When everyone integrates frequently, integration surprises never have time to grow.

๐ŸŒณ Trunk-Based Development Analogy

Imagine building a house. With Gitflow, each worker disappears into their own room for two weeks and builds their part in isolation. When they come back together, nothing quite fits. With trunk-based development, everyone works in the same shared space, commits small changes hourly, and problems are caught and fixed immediately โ€” before they compound.

Bash Scripting โ€” Automating the Boring Stuff

Bash is the native language of Linux. It is not designed to be pretty. The syntax has quirks that will trip you up for years. But it is everywhere โ€” every Linux machine has it, every CI/CD pipeline uses it, every deployment script in the world is written in it or something very similar. You cannot avoid Bash, and once you understand it, you would not want to.

Think of Bash as a set of instructions for a very literal robot assistant. The robot does exactly what each line says, one at a time, from top to bottom. If you need to do a task 100 times, you write it once and the robot does it 100 times. If you need to deploy to 50 servers, you write one loop, not 50 commands.

Variables

#!/bin/bash
# The first line tells the OS which interpreter to use

# Assign a variable (no spaces around the = sign)
NAME="Ushahemba"
APP_PORT=3000

# Use a variable with $
echo "Hello, $NAME"
echo "App runs on port $APP_PORT"

# Command substitution: capture command output into a variable
CURRENT_DATE=$(date +%Y-%m-%d)
echo "Today is $CURRENT_DATE"

Conditionals

# Check if a file exists
if [ -f ".env" ]; then
    echo ".env file found"
else
    echo "No .env file โ€” creating from template"
    cp .env.example .env
fi

# Check if a directory exists
if [ -d "node_modules" ]; then
    echo "Dependencies already installed"
fi

# Compare strings
ENVIRONMENT="production"
if [ "$ENVIRONMENT" = "production" ]; then
    echo "Running in production mode"
fi

# Common test flags:
# -f  file exists and is a regular file
# -d  directory exists
# -z  string is empty
# -n  string is not empty
# -eq equal (numbers)  -ne not equal  -lt less than  -gt greater than

Loops

# Loop over a list of items
for SERVER in web1 web2 web3; do
    echo "Deploying to $SERVER"
    ssh ubuntu@$SERVER "cd /var/www/app && git pull && systemctl restart app"
done

# Loop over files matching a pattern
for FILE in /var/log/nginx/*.log; do
    echo "Processing: $FILE"
    gzip $FILE
done

# While loop
COUNT=1
while [ $COUNT -le 5 ]; do
    echo "Attempt $COUNT"
    COUNT=$((COUNT + 1))
done

Functions

# Define a function
log() {
    echo "[$(date +%H:%M:%S)] $1"
}

deploy_app() {
    local APP_DIR="$1"
    log "Deploying from $APP_DIR"
    cd $APP_DIR
    git pull origin main
    npm install --production
    log "Deploy complete"
}

# Call a function
deploy_app "/var/www/myapp"

Exit Codes and Error Handling

Every command in Linux exits with a code. Zero means success. Anything else means failure. This is how scripts know if the previous step worked before continuing.

# Check the exit code of the last command
git pull
echo "Exit code was: $?"    # 0 = success

# set -e makes the entire script exit if any command fails
# This is the most important line in any deployment script
set -e

# set -u fails if an undefined variable is used (catches typos)
set -u

# Use && to chain commands that should only run if previous succeeded
npm install && npm run build && systemctl restart myapp

Pipelines โ€” Chaining Commands

One of Bash's most powerful features is the pipe (|). It takes the output of one command and feeds it as input to the next. Pipelines let you build sophisticated data processing from simple, single-purpose tools.

# Count how many error lines are in a log file
cat /var/log/app.log | grep "ERROR" | wc -l

# Find the 5 most common errors
grep "ERROR" /var/log/app.log | sort | uniq -c | sort -rn | head -5

# Find all running Node.js processes and show their memory usage
ps aux | grep node | awk '{print $1, $6, $11}'

A Real Deployment Script

Here is a complete, production-quality deployment script that pulls the latest code, installs dependencies, builds the app, and restarts the service โ€” with error handling:

#!/bin/bash
set -euo pipefail  # Exit on error, undefined vars, and pipe failures

# --- Configuration ---
APP_DIR="/var/www/myapp"
APP_SERVICE="myapp"
DEPLOY_BRANCH="main"
LOG_FILE="/var/log/deploy.log"

# --- Helper function ---
log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a $LOG_FILE
}

log "=== Deployment started ==="

# --- Step 1: Pull latest code ---
log "Pulling latest code from $DEPLOY_BRANCH..."
cd $APP_DIR
git pull origin $DEPLOY_BRANCH

# --- Step 2: Install dependencies ---
log "Installing dependencies..."
npm ci --production   # npm ci is faster and more reliable than npm install

# --- Step 3: Build ---
log "Building application..."
npm run build

# --- Step 4: Restart service ---
log "Restarting $APP_SERVICE service..."
systemctl restart $APP_SERVICE

# --- Step 5: Verify it started ---
sleep 3
if systemctl is-active --quiet $APP_SERVICE; then
    log "=== Deployment successful ==="
else
    log "=== ERROR: Service failed to start ==="
    systemctl status $APP_SERVICE
    exit 1
fi

Python for DevOps Automation

Bash is excellent for gluing commands together and orchestrating processes. But when your task involves parsing JSON, making multiple API calls, handling complex logic, or interacting with cloud provider APIs, Python is the better tool. Python is readable, has a rich ecosystem of libraries, and is available on virtually every system.

The Basics You Need for DevOps

# Run a Python script
python3 script.py

# Install a package (pip is Python's package manager)
pip3 install requests boto3 pyyaml
# Reading environment variables (the safe way to handle secrets)
import os

API_KEY = os.environ.get('API_KEY')
if not API_KEY:
    raise ValueError("API_KEY environment variable is required")

APP_URL = os.environ.get('APP_URL', 'http://localhost:3000')
# The second argument is the default value if the variable isn't set
# Making HTTP requests with the requests library
import requests

response = requests.get('https://api.example.com/users', headers={
    'Authorization': f'Bearer {API_KEY}',
    'Content-Type': 'application/json'
})

# Check if request succeeded
response.raise_for_status()   # Raises exception for 4xx/5xx status codes

# Parse the JSON response
data = response.json()        # Converts JSON string to Python dict/list
print(f"Found {len(data['users'])} users")

A Real-World Health Check Script

Here is a Python script that checks whether an application is healthy. If it is not, it sends an alert to a Slack channel. This exact pattern is used in production monitoring systems at every scale.

#!/usr/bin/env python3
"""
Application health check script.
Checks the /health endpoint and sends a Slack alert on failure.
Usage: python3 health_check.py
Environment variables: APP_URL, SLACK_WEBHOOK
"""

import requests
import os
import sys
from datetime import datetime


def check_health(url: str) -> dict:
    """Check the health endpoint. Returns a status dict."""
    try:
        response = requests.get(f"{url}/health", timeout=10)
        if response.status_code == 200:
            return {"status": "healthy", "code": 200}
        else:
            return {
                "status": "unhealthy",
                "code": response.status_code,
                "message": f"Unexpected status: {response.status_code}"
            }
    except requests.exceptions.ConnectionError:
        return {"status": "down", "message": "Connection refused โ€” app is not running"}
    except requests.exceptions.Timeout:
        return {"status": "down", "message": "Request timed out after 10 seconds"}


def send_slack_alert(webhook_url: str, message: str):
    """Send an alert to a Slack channel via webhook."""
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    payload = {
        "text": f"*ALERT* [{timestamp}] {message}"
    }
    try:
        requests.post(webhook_url, json=payload, timeout=5)
    except Exception as e:
        print(f"Failed to send Slack alert: {e}", file=sys.stderr)


def main():
    app_url = os.environ.get("APP_URL", "http://localhost:3000")
    slack_webhook = os.environ.get("SLACK_WEBHOOK")

    result = check_health(app_url)

    if result["status"] == "healthy":
        print(f"OK: {app_url} is healthy")
    else:
        error_msg = result.get("message", "Unknown error")
        print(f"FAIL: {app_url} is {result['status']}: {error_msg}", file=sys.stderr)

        if slack_webhook:
            send_slack_alert(slack_webhook, f"{app_url} is {result['status']}: {error_msg}")

        sys.exit(1)   # Non-zero exit code signals failure to calling scripts


if __name__ == "__main__":
    main()

Python for File and Config Operations

import json
import yaml

# Read a JSON configuration file
with open("config.json") as f:
    config = json.load(f)
    database_url = config["database"]["url"]

# Read a YAML file (Kubernetes configs, CI/CD pipelines use YAML)
with open("deployment.yaml") as f:
    deployment = yaml.safe_load(f)
    image = deployment["spec"]["template"]["spec"]["containers"][0]["image"]
    print(f"Deploying image: {image}")

# Count lines in a log file
with open("/var/log/app.log") as f:
    lines = f.readlines()
    error_count = sum(1 for line in lines if "ERROR" in line)
    print(f"Found {error_count} errors in {len(lines)} total log lines")
๐Ÿ’ก When to Use Bash vs. Python

Use Bash for: running other programs, piping commands together, simple file operations, and deployment scripts that are mostly shell commands with a little glue.

Use Python for: parsing JSON or YAML, making API calls, complex logic, cloud SDK interactions (AWS boto3, GCP libraries), and any script that will grow beyond 20-30 lines.

Even a 5-line script that saves you 10 minutes every day saves you over 60 hours a year. The first time you automate a repetitive task, it pays for itself within a week.

๐Ÿ“Š Fun Fact: Git by the Numbers

GitHub alone hosts over 420 million repositories. The Linux kernel โ€” which Linus Torvalds created Git specifically to manage โ€” has over 1 million commits in its Git history, made by over 21,000 developers over 30+ years. Git was able to store and navigate all of that history. A git log --oneline on the Linux kernel takes less than a second.

Chapter Summary

  • Git is a version control system that saves named checkpoints (commits) of your project and lets you branch, experiment, and merge changes safely.
  • The daily Git workflow: git status โ†’ git add โ†’ git commit โ†’ git push โ†’ git pull.
  • Branches allow parallel development. Keep feature branches short-lived. Trunk-based development (committing to main frequently) works best for CI/CD.
  • Bash scripting automates repetitive tasks. Master variables, conditionals, loops, functions, and exit codes. Always use set -e in deployment scripts.
  • Pipelines (|) are one of Bash's superpowers: chain simple commands into powerful data-processing workflows.
  • Python is the right tool for complex DevOps automation: API calls, JSON parsing, cloud SDK interactions, health checks, and anything that outgrows a simple shell script.
  • Read environment variables for secrets and configuration. Never hardcode credentials in scripts.