Git stash

Uit De Vliegende Brigade
Naar navigatie springen Naar zoeken springen

git stash or stashing, plays a role in conflict resolution; when one or more files have been changed at different locations.

When you "stash" your changes, Git takes your uncommitted changes (both staged and unstaged) and saves them on a stack. This allows you to work on other things without losing your current changes. You can apply the stashed changes back to your working directory when you're ready.

Stash Commands:

  • Stash Changes: git stash
  • List Stashes: git stash list
  • Apply Stash: git stash apply
  • Drop Stash: git stash drop
  • Pop Stash: git stash pop - Applies and removes from stash.

git stash apply

With git stash apply, the stashed changes are incorporated into the 'other' files (e.g., pulled files). Meaning that both pieces of conflicting code are incorporated in the same files, clearly indicated by conflict markers (e.g.: <<<<<<<, =======, >>>>>>>).

In detail:

  • Retrieve the stash: Git retrieves the latest stash (or a specific stash if you specify one) from the stash stack. The stash includes both the changes in the working directory and the changes in the index (staged changes)
  • Apply Changes: Git tries to apply these changes on top of your current working directory. This means it will reintroduce the modifications that were saved in the stash to your current files. If there have been changes to the same files in the meantime (such as from a git pull or other commits), Git will attempt to merge the stashed changes with the current state of those files
  • Conflict Detection: If there are conflicts between the stashed changes and the current state of the working directory, Git will mark these conflicts in the files. You will see the conflict markers (e.g., <<<<<<<, =======, >>>>>>>) within the affected files. The process of resolving these conflicts is the same as any other Git conflict resolution.

Reverse to pre-stash

After git stash and git pull, I realised that my local version was a better basis than what I pulled. Let's reverse this:

  • git stash list: See all stashes. In this case, there is only one: stash@{0}: WIP on main: 020ac01 Update
  • git stash show -p stash@{0}: See all changes, using diff. Here I can clearly see what my changes were and what the remote changes were
  • git stash apply stash@{0}
  • ...Worked!

See also