Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Demonstrate how Git allows switching branches when you have unstaged changes if and only if it can do so without losing data -- for instance if files would need to be merged, or therre are path conflicts.
$ git init myproj && cd myproj
Initialized empty Git repository in C:/tmp/myproj/.git/
$ echo Hello > test.txt
$ git add -A && git commit -m "Initial commit: Hello"
[master (root-commit) dcda84c] Initial commit: Hello
1 file changed, 1 insertion(+)
create mode 100644 test.txt
$ git checkout -b branch1
Switched to a new branch 'branch1'
$ echo Goodbye > test2.txt
$ git add -A && git commit -m "Add Goodbye in test2.txt"
[branch1 052593b] Add Goodbye in test2.txt
1 file changed, 1 insertion(+)
create mode 100644 test2.txt
$ git checkout -b branch2 master
Switched to a new branch 'branch2'
$ echo Bonjour > test.txt
$ git add -A
$ git status
On branch branch2
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
modified: test.txt
$ git checkout branch1
M test.txt
Switched to branch 'branch1'
$ git status
On branch branch1
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
modified: test.txt
$ echo Yes you can switch branches with uncommitted changes
Yes you can switch branches with uncommitted changes
$ echo What > test2.txt # modify file
$ git checkout branch2 # switch branches
error: Your local changes to the following files would be overwritten by checkout:
test2.txt
Please, commit your changes or stash them before you can switch branches.
Aborting
$ echo But you cannot switch branches if it will cause conflicts
But you cannot switch branches if it will cause conflicts
$ git checkout test2.txt # discard unstaged changes to test2.txt
$ git checkout branch2 # switch branches
M test.txt
Switched to branch 'branch2'
$ git status
On branch branch2
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
modified: test.txt
$
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.