BASH

Automate Git Branch Checkout and Pull

A bash script for automating common Git operations: safely switching to a specified branch, pulling the latest changes, and cleaning up merged local branches.

#!/bin/bash
# Automate Git operations: checkout, pull, and clean up branches

TARGET_BRANCH="$1"

if [ -z "$TARGET_BRANCH" ]; then
  echo "Usage: $0 <branch-name>"
  echo "Example: $0 develop"
  exit 1
fi

echo "Attempting to switch to branch '$TARGET_BRANCH' and pull latest changes..."

# Stash any local changes first
git stash save "Stashing local changes before checkout" > /dev/null 2>&1

# Checkout the target branch
if git checkout "$TARGET_BRANCH"; then
  echo "Successfully switched to branch '$TARGET_BRANCH'."
else
  echo "Error: Failed to switch to branch '$TARGET_BRANCH'. Aborting."
  # Attempt to pop stash if it exists
  git stash pop > /dev/null 2>&1
  exit 1
fi

# Pull latest changes
if git pull origin "$TARGET_BRANCH"; then
  echo "Successfully pulled latest changes for '$TARGET_BRANCH'."
else
  echo "Warning: Failed to pull latest changes for '$TARGET_BRANCH'. Manual intervention might be needed."
fi

# Clean up old local branches that have been merged and are not the current branch
echo "Cleaning up merged local branches (excluding current branch)..."
git branch --merged | grep -v "\*" | xargs -n 1 git branch -d

# Apply any stashed changes
if git stash list | grep -q "Stashing local changes"; then
  echo "Applying stashed changes..."
  git stash pop
fi

echo "Git operations completed for branch '$TARGET_BRANCH'."
exit 0
How it works: This script takes a branch name as an argument. It first stashes any local changes to prevent conflicts, then attempts to switch to the specified branch and pull the latest updates from the remote. After syncing, it cleans up local branches that have already been merged into the current branch, and finally, it tries to reapply any stashed changes. This automates common developer workflow steps for deployment or feature switching.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs