Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in DevOps and Agile by (19.4k points)

Context: I'm working on master adding a simple feature. After a few minutes, I realize it was not so simple and it should have been better to work into a new branch.

This always happens to me and I have no idea how to switch to another branch and take all these uncommitted changes with me leaving the master branch clean. I supposed git stash && git stash branch new_branch would simply accomplish that but this is what I get:

~/test $ git status

# On branch master

nothing to commit (working directory clean)

~/test $ echo "hello!" > testing 

~/test $ git status

# On branch master

# Changed but not updated:

#   (use "git add <file>..." to update what will be committed)

#   (use "git checkout -- <file>..." to discard changes in working directory)

#

#   modified:   testing

#

no changes added to commit (use "git add" and/or "git commit -a")

~/test $ git stash

Saved working directory and index state WIP on master: 4402b8c testing

HEAD is now at 4402b8c testing

~/test $ git status

# On branch master

nothing to commit (working directory clean)

~/test $ git stash branch new_branch

Switched to a new branch 'new_branch'

# On branch new_branch

# Changed but not updated:

#   (use "git add <file>..." to update what will be committed)

#   (use "git checkout -- <file>..." to discard changes in working directory)

#

#   modified:   testing

#

no changes added to commit (use "git add" and/or "git commit -a")

Dropped refs/stash@{0} (db1b9a3391a82d86c9fdd26dab095ba9b820e35b)

~/test $ git s

# On branch new_branch

# Changed but not updated:

#   (use "git add <file>..." to update what will be committed)

#   (use "git checkout -- <file>..." to discard changes in working directory)

#

#   modified:   testing

#

no changes added to commit (use "git add" and/or "git commit -a")

~/test $ git checkout master

M   testing

Switched to branch 'master'

~/test $ git status

# On branch master

# Changed but not updated:

#   (use "git add <file>..." to update what will be committed)

#   (use "git checkout -- <file>..." to discard changes in working directory)

#

#   modified:   testing

#

no changes added to commit (use "git add" and/or "git commit -a")

Do you know if there is any way of accomplishing this?

1 Answer

0 votes
by (27.5k points)

You can use the following command:

$ git checkout -b <new-branch>

If you want to leave your current branch as it is, also create and checkout a new branch, and keep all your changes. You can then make a commit with:

$ git add <files>

Then commit to your new branch with the following command:

$ git commit -m "<Brief description of this commit>"

Now remember, you don't reset your original branch, it stays as it is. But the last commit on <old-branch> will still be the same. Therefore you checkout -b and then commit.

Browse Categories

...