A Detailed Explanation of Git Staging and Multitasking

Stashing is a feature that temporarily saves changes made to your workspace. When you need to switch branches to handle an urgent task but don’t want to commit unfinished work, stashing is the best option. Understanding how to use stashing is crucial for multitasking in development.

1. Basic Concepts of Temporary Storage

(1) What Is a Temporary Storage Area?

Staging temporarily saves changes made to the workspace and staging area:

100%
graph TB
    A[Changes have been made to the workspace] --> B[git stash]
    B --> C[Edit and save tostash]
    C --> D[The workspace is now clean]
    D --> E[Switch Branches]
    E --> F[git stash pop]
    F --> G[Restore Changes]
    
    style B fill:#fff3cd
    style D fill:#d4edda
    style G fill:#c3e6cb

(2) The Difference Between "stash" and "commit"

Feature stash commit
Purpose Temporary Storage Permanent Record
History Not in commit history In commit history
Branch Not on any branch On the current branch
Push Notifications No push notifications Push notifications
Use Cases Temporary task switching Completing feature development

(3) The storage structure of stash

A stash is a stack:


2. Basic Temporary Storage Operations

(1) Save the current changes temporarily

▶ Example: Staging Changes

BASH
# View Current Changes
git status

# Output:
# Changes not staged for commit:
#   modified:   src/auth.js
#   modified:   src/user.js

# Save current changes temporarily
git stash

# Output:
# Saved working directory and index state WIP on main: a1b2c3d feat: Add Feature

# View Status(The workspace is clean)
git status

# Output:
# On branch main
# nothing to commit, working tree clean

(2) Staging with a description

▶ Example: Add a description

BASH
# Save for now and add a description
git stash save "WIP: User Login Feature"

# Or usepush(New Grammar)
git stash push -m "WIP: User Login Feature"

# Output:
# Saved working directory and index state On main: WIP: User Login Feature

# View the staging list
git stash list

# Output:
# stash@{0}: On main: WIP: User Login Feature

(3) Staging includes untracked files

▶ Example: Includes untracked files

BASH
# Create a New File(Not tracked)
touch new-file.js

# DefaultstashUntracked files will not be saved
git stash

# Output:
# Saved working directory and index state WIP on main: a1b2c3d
# new-file.js still untracked

# Usage-uThe selection includes untracked files
git stash -u

# Or
git stash --include-untracked

# Usage-aThe option includes all files(Include ignored files)
git stash -a

3. Viewing and Managing Staging

(1) View the staging list

▶ Example: List all staging areas

BASH
# View the staging list
git stash list

# Output:
# stash@{0}: On main: WIP: User Login Feature
# stash@{1}: On feature: WIP: Shopping Cart Feature
# stash@{2}: On develop: FixBug

# Limit the number of items displayed
git stash list -3

# View Staging Details
git stash show

# Output:
#  src/auth.js | 10 ++++++++++
#  src/user.js |  5 ++---
#  2 files changed, 12 insertions(+), 3 deletions(-)

# View Detailed Differences
git stash show -p

# View a Specific Cache
git stash show stash@{1}

(2) View Staged Content

▶ Example: Viewing Staging Details

BASH
# View the latest full diff from the staging area
git stash show -p stash@{0}

# Output:
# diff --git a/src/auth.js b/src/auth.js
# index abc1234..def5678 100644
# --- a/src/auth.js
# +++ b/src/auth.js
# @@ -10,6 +10,16 @@ function validate() {
# +  // Added validation logic
# +  if (!token) {
# +    return false;
# +  }
#    return true;
#  }

# View Cached Statistics
git stash show --stat

# Output:
#  src/auth.js | 10 ++++++++++
#  src/user.js |  5 ++---
#  2 files changed, 12 insertions(+), 3 deletions(-)

(3) Delete the staging area

▶ Example: Deleting a staging area

BASH
# Delete the latest staging
git stash drop

# Delete Specified Stash
git stash drop stash@{2}

# Clear All Cache
git stash clear

# Confirm Deletion
git stash list

4. Application Staging

(1) Apply and pop the staging area

▶ Example: Application Staging

BASH
# Apply, Save, and Delete
git stash pop

# Output:
# On branch main
# Changes not staged for commit:
#   modified:   src/auth.js
#   modified:   src/user.js

# Use Specified Stash
git stash pop stash@{1}

# If there is a conflict
# CONFLICT (content): Merge conflict in src/auth.js
# The stash entry is kept in case you need it again.

# After Resolving the Conflict,Manually Delete the Stash
git stash drop

(2) Apply but keep in staging (apply)

▶ Example: Keep in Stash

BASH
# App is cached but not deleted
git stash apply

# Use Specified Stash
git stash apply stash@{1}

# View the staging list(The temporary file is still there)
git stash list

# Output:
# stash@{0}: On main: WIP: User Login Feature
# stash@{1}: On feature: WIP: Shopping Cart Feature

# applySuitable for multiple uses of the same temporary storage

(3) pop vs apply

100%
graph TB
    A[App Stash] --> B{Method}
    B -->|pop| C[Apply and Clear the Clipboard]
    B -->|apply| D[Apply but keep in the staging area]
    C --> E[Single-use]
    D --> F[Reusable]
    
    style C fill:#d4edda
    style D fill:#fff3cd

Scenarios for using pop:

When to use apply:


5. Detailed Explanation of Temporary Storage Options

(1) Common Temporary Storage Options

Option Description Use Case
save Save to Clipboard (Old Syntax) Basic Clipboard
push Save to Clipboard (New Syntax) Recommended
-m Add description Mark as draft
-u Includes untracked files New files must also be staged
-a Include all files Include ignored files
-k Keep staging area Stage workspace only

▶ Example: Using the "Temporary Storage" option

BASH
# Only cache changes to tracked files
git stash

# Check-in includes untracked files
git stash -u

# Check out includes ignored files
git stash -a

# Temporary Workspace Only,Reserve a buffer
git stash -k

# Cache only specific files
git stash push src/auth.js

# Cache only files that match the pattern
git stash push '*.js'

# Preserve the temporary storage index
git stash --index

(2) Creating a Branch from a Stash

▶ Example: Creating a branch from a staging area

BASH
# Create a New Branch from a Stash
git stash branch feature-from-stash

# Output:
# Switched to a new branch 'feature-from-stash'
# On branch feature-from-stash
# Changes not staged for commit:
#   modified:   src/auth.js

# This will create a new branch and apply the staged changes.
# Ideal for transferring staged changes to a new branch for development

6. Save Workflow

(1) Emergency Task Switching

▶ Example: Handling an Urgent Bug

BASH
# Features currently under developmentA
echo "feature A code" > feature-a.js
git status

# Output:
# Untracked files:
#   feature-a.js

# Sudden need for urgent repairsBug
# Save the current work
git stash save "WIP: FeaturesAUnder development"

# Switch tohotfixBranch
git checkout -b hotfix-urgent-bug

# FixBug
echo "fix" > fix.js
git add fix.js
git commit -m "fix: Urgent FixBug"

# Push Fix
git push origin hotfix-urgent-bug

# Switch back to the original branch and resume work
git checkout main
git stash pop

# Continue Developing FeaturesA

(2) Parallel Development of Multiple Tasks

100%
sequenceDiagram
    participant Developer
    participant mainBranch
    participant featureBranch
    participant Stash
    
    Developer->>mainBranch: Development FeaturesA
    Developer->>Stash: git stash Save A
    Developer->>featureBranch: Switch to Branch DevelopmentB
    Developer->>Stash: git stash Save B
    Developer->>mainBranch: Cut back tomain
    Developer->>Stash: git stash pop Restore A

▶ Example: Switching Between Tasks

BASH
# Development FeaturesA
echo "feature A" > feature-a.js
git stash push -m "FeaturesA"

# Toggle Development FeaturesB
git checkout -b feature-b
echo "feature B" > feature-b.js
git stash push -m "FeaturesB"

# View the staging list
git stash list

# Output:
# stash@{0}: On feature-b: FeaturesB
# stash@{1}: On main: FeaturesA

# Back tomainContinue DevelopmentA
git checkout main
git stash pop stash@{1}

# Completed FeaturesA
git add feature-a.js
git commit -m "feat: FeaturesADone"

# Cut tofeature-bContinue DevelopmentB
git checkout feature-b
git stash pop

(3) Staging the application to a different branch

▶ Example: Staging Changes Across Branches

BASH
# Staging Changes on feature Branch
git checkout feature
echo "some changes" > file.js
git stash save "Share Edits"

# Switch tomainBranch Application Staging
git checkout main
git stash apply

# NowmainThese changes are also present in the branch.
# The temporary file is still there,Can be applied to other branches

# Switch todevelopBranch Applications
git checkout develop
git stash apply

# Delete Stash
git stash drop

7. Best Practices for Temporary Storage

(1) Recommendations for Temporary Storage

Best Practices:

BASH
# Add a clear description
git stash save "WIP: User Authentication Feature,Complete the login logic"

# Clear the cache list periodically
git stash list
git stash drop stash@{5}  # Delete the old staging area

# Usageapplyrather thanpop,If you're not sure whether you still need it
git stash apply

# Check the status before saving temporarily
git status
git diff

Bad Practices:

BASH
# No description,Difficult to identify
git stash

# Retaining large amounts of temporary data over the long term
git stash list  # Dozens of temporary files

# Forgot to restore the staging area
git stash
# ... A few days later, I forgot what I had saved.

(2) Handling Conflicts in the Staging Area

▶ Example: Resolving Staging Conflicts

BASH
# Conflicts caused by app cache
git stash pop

# Output:
# CONFLICT (content): Merge conflict in src/auth.js
# The stash entry is kept in case you need it again.

# View Conflicting Files
git status

# Resolving Conflicts
# Editing Files with Conflicts,Keep the necessary content

# Mark the conflict as resolved
git add src/auth.js

# Delete Stash
git stash drop

# Or discard the temporary file
git reset --hard
git stash drop

(3) Temporary Storage Management Script

▶ Example: Staging Management Tool

BASH
#!/bin/bash
# stash-manager.sh - Cache Management Tool

case "$1" in
    list)
        echo "=== Stash List ==="
        git stash list
        ;;
    show)
        if [ -z "$2" ]; then
            git stash show -p
        else
            git stash show -p "stash@{$2}"
        fi
        ;;
    apply)
        if [ -z "$2" ]; then
            git stash apply
        else
            git stash apply "stash@{$2}"
        fi
        ;;
    drop)
        if [ -z "$2" ]; then
            git stash drop
        else
            git stash drop "stash@{$2}"
        fi
        ;;
    clear)
        read -p "Clear all stashes? (y/n) " -n 1 -r
        echo
        if [[ $REPLY =~ ^[Yy]$ ]]; then
            git stash clear
            echo "All stashes cleared"
        fi
        ;;
    *)
        echo "Usage: $0 {list|show [n]|apply [n]|drop [n]|clear}"
        ;;
esac

❓ FAQ

Q What is the difference between stash and commit?
A A stash is a temporary save; it does not appear in the commit history, is not pushed, and does not belong to any branch. A commit is a permanent record; it appears in the commit history, is pushed, and belongs to the current branch.
Q What is the difference between stash pop and stash apply?
A pop applies the commit and deletes the commit record, while apply applies the commit but retains the commit record. If you need to apply the same commit multiple times, use apply.
Q Does stash save untracked files?
A By default, no. Use git stash -u or git stash --include-untracked to include untracked files. Use git stash -a to include all files (including ignored files).
Q How do I view the contents of the staging area?
A Use git stash list to view the staging list, git stash show to view staging statistics, and git stash show -p to view the complete differences in the staging list.
Q What should I do if a conflict occurs when staging an app?
A To resolve conflicts in a file, use git add to mark the conflict as resolved, then use git stash drop to remove the changes from staging. If you want to discard the changes, use git reset --hard and git stash drop.

📖 Summary


📝 Exercises

  1. Basic Exercise: After modifying a file, use stash to stash the changes, view the stash list and details, and then apply the stash to experience the complete stashing process.

  2. Advanced Exercise: Simulate a scenario where you need to switch tasks urgently: While developing a feature, stash your current work, switch branches to fix a bug, then restore the stash and continue development to experience the practical application of stashing.

  3. Challenge: Experience parallel development of multiple tasks: Create multiple staging areas, switch between different branches to apply different staging areas, and understand how the staging stack works.

Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏