DEV Community

Cover image for Switch Branches in Git Without Losing Your Work

Switch Branches in Git Without Losing Your Work

Asad Bukhari on September 02, 2024

As developers, we often find ourselves in situations where we're deep into coding a feature when suddenly an urgent issue demands our immediate att...
Collapse
 
doncallisto profile image
Samuele Lilli

There's at least another solution:

  • push your branch as it is (without the current work) to remote
  • commit all changes to current branch with a commith you're gonna reset after
  • do whatever job you need to on the other branch
  • switch back to previous branch
  • reset to HEAD~1
  • continue your work

This is my preferred way as, with stash, you can inadvertently pop back changes that would mess up all the things and with your second scenario you need to do a lot of extra ("useless") work.

Collapse
 
asadbukhari profile image
Asad Bukhari

You're absolutely right, there are many different methods people use to achieve the same result in Git. Thank you for sharing your preferred approach! It’s always great to learn about different techniques and perspectives. Appreciate your input!

Collapse
 
xuandinhgl profile image
Xuan Dinh

Use git worktree, it's really useful when you need to switch to a different branch while working
Ex: git worktree ../<dir_name> <branch name>

Collapse
 
matthewpersico profile image
Matthew O. Persico

Disk is cheap. Every time you start a branch to do some work, make a worktree. Switching contexts is now as simple as 'cd'. No work lost. You just need discipline to do that EVERY TIME you need to make a branch. I have written a framework around that workflow if you're interested: github.com/matthewpersico/personal > But be forewarned - it's involved.

Collapse
 
seanbracksdev profile image
SeanBracksDev

Good info!

However it’s good practice to use things like git switch or git branch rather than git checkout for everything now.

Collapse
 
aless10 profile image
Alessio Izzo

Or just clone the repo again in another folder.
Btw I think that git worktree is THE solution to this, but I also use the git stash approach

Collapse
 
khuongduybui profile image
Duy K. Bui

Check out GitButler.

Collapse
 
ahmad_ali_786 profile image
ahmad ali

Outstanding,
Very informative good job :)

Collapse
 
phpartisanmakeweeb profile image
phpArtisanMakeWeeb

It's me, or this post reeks of AI?

Collapse
 
odrinr profile image
odrinr

increíble... buen dato gracias por tomar parte de tu tiempo y compartir esta valiosa información.

Collapse
 
tomaszprasolek profile image
Tomasz Prasołek • Edited

I always commit my code with the message "WIP" only or "WIP: what I am doing". I always work on some feature branch, so I don't have to create a temporary branch.

I have never in my life used git stash command :)