Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to switch and save without commit in git?

Tags:

git

github

I am working on one branch, and suddenly I have to switch to another branch to fix an urgent bug. The problem is the changes I make to the current branch is still a mess and I do not want to commit that and leave some scrappy commit message.

Is there any way I can save the current changes without commit?

like image 854
Justin Li Avatar asked Jul 27 '17 13:07

Justin Li


People also ask

How do I keep changes on a branch without committing?

The "git stash" command can help you to (temporarily but safely) store your uncommitted local changes - and leave you with a clean working copy.

Can I switch branches with uncommitted changes?

You may switch branches with uncommitted changes in the work-tree if and only if said switching does not require clobbering those changes. That is—and please note that this is still simplified; there are some extra-difficult corner cases with staged git add s, git rm s and such—suppose you are on branch1 .

Do I need to commit before switching branch?

You must commit or stash those changes first before switching branches. You can think of stash as a drawer to store uncommitted changes temporarily. Stashing allows you to put aside the “dirty” changes in your working tree and continue working on other things in a different branch on a clean slate.


2 Answers

Yes, you can use stash.

git stash

It will save any uncommitted stuff in a special area where you can get it back later using

git stash apply

You can see what is in the stash with

git stash list
like image 101
Dan Lowe Avatar answered Sep 19 '22 06:09

Dan Lowe


Stash obviously works. I just want to propose that it is also a viable, if not better, option, to just commit whatever you have got, for the following reasons:

  1. Stash is kept separately from the current branch, the index, and the working space, and less visible. Unless you are going to fix the other issue and switch back real quick, it's actually easier to get confused with the state of the stash after a while.
  2. Committing your changes in your environment does not affect anything or anybody else, as long as you don't push the commit. You can always reorganize your commits later when you are done with the feature. Compared to stash, a commit on the feature branch where it belongs is easier to manage later.
like image 26
jingx Avatar answered Sep 20 '22 06:09

jingx