Git Stash Example: Save Work & Deploy Hotfixes Fast 2025

The 3 AM Production Crisis Scenario

Picture this: It’s 3 AM, and you’re deep in the middle of refactoring a complex Terraform module for your company’s AWS infrastructure. You’ve got half-written resource definitions, modified variable files, and updated outputs scattered across multiple files. Suddenly, your phone explodes with alerts—production is down. The payment processing service is failing, and every minute of downtime costs thousands in revenue.

Your manager is calling. The on-call engineer needs an immediate hotfix. But here’s the problem: your working directory is a mess of uncommitted changes that aren’t ready for production. You can’t commit this half-finished work, but you also can’t afford to lose hours of progress.

This is where git stash in DevOps emergency fixes becomes your production lifeline.

“Before diving into stash usage, make sure you understand the basics like cloning, committing, and viewing logs — covered in Git Basics for DevOps

Emergency Git Stash Workflow: Visual Overview

Production Alert! 🚨
         ↓
   [Working on Feature]
         ↓
   git stash push -m "..."  ← Save current work
         ↓
   git checkout main        ← Switch to stable branch
         ↓
   git checkout -b hotfix/... ← Create emergency branch
         ↓
   [Implement Hotfix]       ← Focus on production issue
         ↓
   [Deploy & Verify]        ← Push through CI/CD pipeline
         ↓
   git checkout feature     ← Return to original work
         ↓
   git stash pop           ← Restore previous progress
         ↓
   [Continue Development]   ← Back to normal workflow

Emergency Git Stash Workflow - Git Stash Example - www.thedevopstooling.com
Emergency Git Stash Workflow – Git Stash Example – http://www.thedevopstooling.com

Why Git Stash Is Essential for DevOps Engineers

In traditional software development, you might have the luxury of finishing your current task before switching contexts. DevOps doesn’t offer that comfort. Production issues demand immediate attention, and your ability to rapidly context-switch without losing work can mean the difference between a 5-minute outage and a multi-hour crisis.

Git stash serves as your emergency parachute, allowing you to:

  • Instantly save uncommitted changes without creating messy commits
  • Switch branches immediately to address urgent production issues
  • Preserve complex work-in-progress that took hours to create
  • Maintain clean git history for debugging and automated release notes
  • Resume exactly where you left off after resolving the crisis

For complete command reference, visit the official Git stash docs

Why Clean Git History Matters in DevOps

A clean commit history isn’t just aesthetic—it’s critical for DevOps operations. When you run git log or git blame during incident response, you need to quickly understand:

  • What changed and when during previous deployments
  • Who made critical infrastructure modifications for rapid communication
  • Why specific changes were made through clear commit messages
  • Automated release note generation for compliance and documentation

Using git stash prevents “WIP”, “temp fix”, and “oops” commits from polluting this valuable operational history.

Step-by-Step Guide: Git Stash in Action

Let’s walk through the emergency scenario using practical git stash commands that every DevOps engineer should master.

Step 1: Save Your Uncommitted Changes

When production alerts start firing, your first move is securing your current work:

# Quick stash with automatic message
git stash

# Better: Stash with descriptive message
git stash push -m "WIP: Terraform module refactor for multi-region deployment"

# Stash specific files only (if needed)
git stash push -m "Partial database migration scripts" -- db/migrations/ config/database.yml

# Include untracked files (-u is shorthand for --include-untracked)
git stash push -u -m "New monitoring scripts and config files"

💡 Pro Tip: The git stash push -m command is your best friend because it creates a meaningful description. Six months later, when you’re cleaning up old stashes, “WIP: Terraform module refactor” is infinitely more helpful than “WIP on feature-branch: a1b2c3d.”

Step 2: Verify Your Stash and Switch Context

# Confirm your changes are safely stashed
git stash list
# Output: stash@{0}: On feature-terraform-refactor: WIP: Terraform module refactor for multi-region deployment

# Check working directory is clean
git status
# Output: On branch feature-terraform-refactor
# nothing to commit, working tree clean

# Switch to main branch for hotfix
git checkout main

# Create emergency hotfix branch
git checkout -b hotfix/payment-service-timeout

Step 3: Implement and Deploy Your Hotfix

With your work safely stashed, you can focus entirely on the production issue:

# Make necessary changes for the hotfix
vim services/payment/timeout_config.tf

# Commit the hotfix
git add .
git commit -m "hotfix: increase payment service timeout from 30s to 60s"

# Push and deploy through your CI/CD pipeline
git push origin hotfix/payment-service-timeout

Step 4: Return to Your Previous Work

Once the production fire is extinguished:

# Switch back to your feature branch
git checkout feature-terraform-refactor

# Restore your stashed changes
git stash pop
# This applies the stash and removes it from the stash list

# Alternative: Apply without removing from stash list
git stash apply stash@{0}

Advanced Technique: Git Stash Branch for Conflict Resolution

Here’s a pro-level git stash technique that can save hours during complex emergency scenarios:

The Problem: Merge Conflicts After Emergency Fixes

Sometimes, the hotfix you deployed conflicts with your stashed work. When you try git stash pop, you get merge conflicts that are difficult to resolve. This commonly happens when:

  • Your stashed changes modified the same configuration files as your hotfix
  • Team members pushed updates while you were handling the emergency
  • Infrastructure definitions changed during your emergency response

The Solution: Git Stash Branch

git stash branch creates a new branch from the original commit where you created the stash, then applies the stash to that branch. This often eliminates merge conflicts entirely:

# Instead of fighting merge conflicts with git stash pop
git stash branch recover-terraform-work stash@{0}

# This command:
# 1. Creates branch 'recover-terraform-work' from the original commit
# 2. Checks out the new branch  
# 3. Applies the stash
# 4. Removes the stash from the stash list (if successful)

# Now you can merge your recovered work cleanly
git checkout feature-terraform-refactor
git merge recover-terraform-work

# Clean up the temporary recovery branch
git branch -d recover-terraform-work

When to Use Git Stash Branch

ScenarioUse git stash popUse git stash branch
No conflicts expected✅ Simple and fast❌ Unnecessary overhead
Merge conflicts likely❌ Creates messy conflicts✅ Clean conflict resolution
Uncertain about conflicts❌ Risk of corruption✅ Safe fallback option
Multiple team members active❌ High conflict probability✅ Isolated recovery environment

DevOps Takeaway: When emergency fixes involve the same infrastructure components as your stashed work, git stash branch is your conflict-avoidance superpower.

Advanced Git Stash Management for DevOps Teams

Working with Multiple Stashes

DevOps engineers often juggle multiple contexts. Here’s how to manage several stashes effectively:

# Create multiple named stashes
git stash push -m "Database migration scripts - urgent security patch"
git stash push -m "Kubernetes deployment optimization"
git stash push -m "Monitoring dashboard configuration"

# View all stashes
git stash list
# stash@{0}: On main: Monitoring dashboard configuration
# stash@{1}: On feature-k8s: Kubernetes deployment optimization  
# stash@{2}: On security-patch: Database migration scripts - urgent security patch

# Apply specific stash by reference
git stash apply stash@{2}

# Drop specific stash after you no longer need it
git stash drop stash@{1}

# ⚠️ DANGER: Clear all stashes (DESTRUCTIVE OPERATION)
git stash clear

🚨 Critical Warning for DevOps Teams: git stash clear is a destructive operation that permanently deletes ALL stashes. In DevOps environments where a single stash might contain hours of infrastructure configuration work, this command can cause devastating data loss. Never use git stash clear in production workflows. Instead, use the more conservative git stash drop stash@{n} approach to remove individual stashes after meticulously verifying their contents with git stash show -p stash@{n}.

### Stashing Untracked Files

Sometimes your DevOps work includes new configuration files or scripts that Git isn't tracking yet:

```bash
# Stash including untracked files
git stash push -u -m "New monitoring scripts and config files"

# Stash everything including ignored files (rarely needed)
git stash push -a -m "Complete workspace snapshot including build artifacts"

Common Git Stash Pitfalls in DevOps Scenarios

Merge Conflicts When Applying Stash

The most frequent issue occurs when your stashed changes conflict with commits made while working on the hotfix:

# When stash pop fails due to conflicts
git stash pop
# Auto-merging terraform/main.tf
# CONFLICT (content): Merge conflict in terraform/main.tf
# The stash entry is kept in case you need it again.

# Resolve conflicts manually, then
git add terraform/main.tf
git stash drop stash@{0}  # Remove the successfully applied stash

Accidentally Losing Stashed Changes

Prevent data loss with these safety practices:

# Always check what's in a stash before dropping it
git stash show -p stash@{0}

# Create a backup branch from stash if it contains critical work
git stash branch backup-terraform-work stash@{0}

Stashing When Directory Is Not Clean

A common mistake is trying to switch branches when you have both staged and unstaged changes:

# This approach handles both staged and unstaged changes
git stash push -m "Mixed staged and unstaged changes" --include-untracked

Git Stash Best Practices for DevOps Teams

1. Always Use Descriptive Messages

# Poor practice
git stash

# Best practice
git stash push -m "Ansible playbook updates for K8s cluster upgrade - 70% complete"

2. Regular Stash Hygiene

# Weekly cleanup of old stashes
git stash list | head -10  # Review oldest stashes
git stash clear  # Only when you're certain they're no longer needed

3. Critical Work Gets Committed First

Before any major emergency response, commit critical infrastructure changes:

# Quick commit for safety before emergency context switch
git add terraform/critical-infrastructure.tf
git commit -m "WIP: Critical infrastructure changes - safe checkpoint"
git stash push -m "Remaining non-critical changes"

4. Team Communication

In team environments, document your emergency process:

# Include branch and stash info in team communications
git stash push -m "Load balancer config changes - switching to prod issue #TICKET-123"
# Slack: "Stashed my load balancer work to fix payment gateway issue. Back in 30min."

Git Stash Example: Real DevOps Emergency Response

Here’s a complete git stash example showing a realistic DevOps emergency scenario:

# Initial situation: Working on infrastructure updates
$ git status
On branch feature/infrastructure-updates
Changes not staged for commit:
  modified:   terraform/modules/vpc/main.tf
  modified:   ansible/playbooks/security-updates.yml
  modified:   kubernetes/monitoring/prometheus-config.yaml

# Emergency: Production database connection issues
$ git stash push -m "Infrastructure updates: VPC, security, monitoring configs"
Saved working directory and index state On feature/infrastructure-updates: Infrastructure updates: VPC, security, monitoring configs

# Quick hotfix workflow
$ git checkout main
$ git checkout -b hotfix/database-connection-pool
$ vim terraform/modules/database/variables.tf  # Increase connection pool size
$ git add . && git commit -m "hotfix: increase database connection pool size to handle load spike"
$ git push origin hotfix/database-connection-pool

# Deploy hotfix through CI/CD, verify production is stable

# Return to previous work
$ git checkout feature/infrastructure-updates
$ git stash pop
On branch feature/infrastructure-updates
Changes not staged for commit:
  modified:   terraform/modules/vpc/main.tf
  modified:   ansible/playbooks/security-updates.yml
  modified:   kubernetes/monitoring/prometheus-config.yaml

# Back to normal development

Why Git Stash Matters in CI/CD Pipelines

Modern DevOps workflows integrate git stash seamlessly with automated deployment pipelines and incident response procedures. When your monitoring systems detect anomalies or when emergency patches need deployment, git stash enables rapid branch switching without breaking your development flow.

DevOps Incident Response Benefits:

  • Hotfix deployment speed: Switch from feature work to emergency fixes in seconds
  • Zero work loss: Never sacrifice hours of infrastructure configuration during crises
  • Clean deployment history: Maintain professional commit logs for audit trails
  • Team coordination: Multiple engineers can handle different aspects of the same incident

Consider this Jenkins pipeline scenario for emergency deployments:

// Jenkins Pipeline Example - Emergency Deployment
stage('Emergency Hotfix Check') {
    when {
        anyOf {
            branch 'hotfix/*'
            environment name: 'EMERGENCY_DEPLOY', value: 'true'
        }
    }
    steps {
        // Pipeline can trigger while developers have stashed work
        sh 'git stash list'  // Log any stashes for debugging
        sh 'terraform plan'
        sh 'terraform apply -auto-approve'
    }
}

💡 Internal Resource: Learn more about integrating Git workflows with automated deployments in our CI/CD Pipeline Best Practices guide.

Git Stash vs. Alternative Solutions

Understanding when NOT to use git stash is equally important for DevOps incident response:

ScenarioBest SolutionWhy
Emergency production issuegit stash push -m "..."Instant context switching
Experimental infrastructure changesgit stash push -m "..."Safe to discard if needed
Logical checkpoint reachedgit commit -m "..."Preserves development history
Team collaboration neededgit commit -m "..." + git pushEnables team access
Long-term infrastructure projectgit commit -m "..."Maintains project timeline
Stable configuration changesgit commit -m "..."Part of permanent record

DevOps Decision Rule: If your changes represent a logical checkpoint or need team collaboration, commit them. If you’re in the middle of complex work and need to emergency-switch contexts, stash them.

💡 Internal Resource: For more foundational Git concepts, check out our Git Basics for DevOps: Clone, Commit, and Log Explained guide.

Frequently Asked Questions

What’s the difference between git stash pop and git stash apply?

Key Differences:

  • git stash pop: Applies the stash AND removes it from your stash list
  • git stash apply: Applies the stash but KEEPS it in your stash list for future reference

DevOps Emergency Recommendation:

  • Use git stash pop when you’re confident the stash applied cleanly
  • Use git stash apply when you want to test the restoration before permanently removing the stash

Can I stash only specific files during an emergency?

Yes! Use git stash push -- <file1> <file2> to stash specific files.

DevOps Use Cases:

  • Stash only infrastructure files: git stash push -m "VPC configs" -- terraform/vpc/*.tf
  • Stash monitoring configs only: git stash push -m "Prometheus rules" -- monitoring/
  • Separate application code from infrastructure changes during hotfix deployment

Is git stash safe for production workflows?

Absolutely safe. Git stash operates entirely in your local repository and never affects:

  • Remote branches or repositories
  • Deployed production code
  • Team members’ working directories
  • CI/CD pipeline execution

However: Always ensure your production hotfixes follow standard deployment procedures and testing protocols.

How long can I keep changes in a stash?

Technical limit: Git stashes persist indefinitely until manually removed.

DevOps Best Practice: Resolve stashes within 24-48 hours to prevent:

  • Accumulation of forgotten work-in-progress
  • Confusion during team handoffs
  • Merge conflicts from outdated stashed changes
  • Mental overhead from managing multiple old stashes

What happens if I accidentally stash uncommitted work and can’t remember what was stashed?

Recovery Commands:

# See detailed diff of stash contents
git stash show -p stash@{0}

# View stash summary
git stash show stash@{0}

# List all stashes with timestamps
git stash list --format='%gD: %gs (%cr)'

Can I recover a dropped stash?

Limited Recovery Options:

# Find unreachable commits (sometimes works)
git fsck --unreachable | grep commit

# Examine potential stash commits
git show &lt;commit-hash>

DevOps Reality Check: Recovery isn’t guaranteed. Prevention is better than cure—always use git stash show -p before dropping important stashes.

Advanced Scenarios: Git Stash in Complex DevOps Workflows

Multi-Environment Emergency Response

When managing multiple environments (dev, staging, production), you might need to apply the same stashed changes across different branches:

# Stash your monitoring configuration changes
git stash push -m "Prometheus alerting rules for memory optimization"

# Apply to development environment
git checkout develop
git stash apply
git commit -m "Add memory optimization alerts to dev environment"

# Apply to staging environment  
git checkout staging
git stash apply
git commit -m "Add memory optimization alerts to staging environment"

# Apply to production (after testing)
git checkout main
git stash apply
git commit -m "Add memory optimization alerts to production environment"

# Clean up the stash
git stash drop stash@{0}

Handling Stash in Terraform Workflows

Terraform state files require special consideration:

# Never stash terraform.tfstate files
echo "*.tfstate*" >> .gitignore
git add .gitignore
git commit -m "Ignore Terraform state files"

# Stash only configuration files
git stash push -m "Terraform infrastructure changes" -- *.tf *.tfvars

Integrating Git Stash with DevOps Tools

Pre-commit Hooks and Stash

Configure pre-commit hooks that work seamlessly with stash workflows:

#!/bin/bash
# .git/hooks/pre-commit
if git stash list | grep -q "emergency"; then
    echo "Warning: Emergency stash detected. Ensure all critical changes are committed."
    exit 1
fi

IDE Integration for Faster Emergency Response

Modern IDEs like VS Code offer git stash integration that speeds up emergency workflows:

// VS Code settings.json for DevOps teams
{
    "git.enableSmartCommit": true,
    "git.confirmSync": false,
    "git.autofetch": true,
    "gitlens.gitCommands.stashAll.enabled": true
}

Monitoring and Alerting for Stash Usage

Track stash usage patterns in your DevOps team:

# Create alias for stash monitoring
git config alias.stash-report "!git stash list --format='%gD: %gs (%cr)' | head -20"

# Weekly team stash review
git stash-report

Git Stash Best Practices Checklist for DevOps Teams

Before Emergency Response

  • [ ] Use descriptive stash messages that include ticket numbers
  • [ ] Verify critical infrastructure changes are committed before stashing experimental work
  • [ ] Document the emergency context for team awareness
  • [ ] Check that your stash doesn’t include sensitive credentials or API keys

Critical Commands for Emergency Prep:

# Always use descriptive messages
git stash push -m "K8s monitoring setup - ticket #INFRA-455"

# Safety commit for critical work
git add terraform/production/
git commit -m "WIP: Production infrastructure - safe checkpoint"

During Emergency Response

  • [ ] Apply stashes in clean working directories to avoid conflicts
  • [ ] Test stash restoration with git stash apply before using git stash drop
  • [ ] Communicate your stash status to team members during incident response
  • [ ] Use git stash show -p to verify stash contents before applying

Key Emergency Commands:

# Safe stash application workflow
git stash apply stash@{0}  # Test first
git stash drop stash@{0}   # Remove only after verification

# Conflict resolution superpower
git stash branch emergency-recovery stash@{0}

After Emergency Resolution

  • [ ] Clean up resolved stashes within 48 hours to prevent accumulation
  • [ ] Document lessons learned from the emergency response workflow
  • [ ] Review and improve stash naming conventions based on incident patterns
  • [ ] Update team runbooks with successful stash workflows and emergency procedures

Post-Incident Commands:

# Stash cleanup and review
git stash list --format='%gD: %gs (%cr)'  # Review with timestamps
git stash show -p stash@{n}                # Verify before cleanup
git stash drop stash@{n}                   # Conservative individual cleanup

Conclusion: Git Stash as Your DevOps Survival Tool

Git stash isn’t just a convenience feature for developers—it’s an essential survival tool for DevOps engineers managing production environments. In the high-stakes world of infrastructure management and incident response, your ability to instantly preserve work-in-progress while responding to emergencies can save both your sanity and your company’s revenue.

Master These Core Commands:

  • git stash push -m "descriptive message" – Your emergency parachute
  • git stash pop – Quick restoration for simple scenarios
  • git stash branch <name> stash@{n} – Conflict-free recovery for complex situations
  • git stash list – Inventory management for multiple contexts

The next time production alerts wake you up at 3 AM, remember that git stash gives you superpowers: you can teleport between contexts without losing your place, respond to emergencies without sacrificing progress, and maintain clean, professional git history even in chaos.

Key Takeaway: Master git stash now, before the emergency happens. Practice the commands, establish team conventions, and integrate stash workflows into your incident response procedures. When production breaks and every second counts, muscle memory with git stash best practices will help you save the day—and your work.

Start incorporating these git stash emergency workflows into your daily DevOps practice. Your future self (and your teammates) will thank you when the next production crisis hits.

📚 Next Steps: Explore our complete DevOps Emergency Response Toolkit for comprehensive incident management strategies.

Stashing often happens when you’re juggling multiple branches. If you’re curious about branching best practices, check out our guide on Git Branching Strategies

Similar Posts

2 Comments

Leave a Reply