Consider the following "story":
$ mkdir my_project
$ cd my_project
$ git init
Initialized empty Git repository in /home/misha/misha/my_project/.git/
$ echo "first line" > hello.txt
$ git add hello.txt
$ git commit -m "first commit"
[master (root-commit) 9c913a1] first commit
1 files changed, 1 insertions(+), 0 deletions(-)
create mode 100644 hello.txt
$ git branch new_feature
$ git checkout new_feature
Switched to branch 'new_feature'
$ echo "second line" >> hello.txt
$ cat hello.txt
first line
second line
$ git checkout master
M hello.txt
Switched to branch 'master'
$ cat hello.txt
first line
second line
Why hello.txt
has two lines on branch master? (I thought that git checkout
will revert the working directory to the previous state, i.e. hello.txt
will have only one line.)
What actually happens behind the scenes to the working directory on git checkout
? How it is updated?
Git Checkout File Checking out a file is similar to using git reset with a file path, except it updates the working directory instead of the stage. Unlike the commit-level version of this command, this does not move the HEAD reference, which means that you won't switch branches.
To change this current working directory, you can use the "cd" command (where "cd" stands for "change directory"). For example, to move one directory upwards (into the current folder's parent folder), you can just call: $ cd ..
The working tree, or working directory, consists of files that you are currently working on. You can think of a working tree as a file system where you can view and modify files. The index, or staging area, is where commits are prepared. The index compares the files in the working tree to the files in the repo.
Checkout an Existing Branch Generally, Git won't let you checkout another branch unless your working directory is clean, because you would lose any working directory changes that aren't committed.
Your git checkout to master prevents you from losing uncommitted changes. Thats why you still have your second line in your hello.txt
file. If you really want to lose your uncommitted changes you have to use the -f
parameter.
Finally your checkout would look like this:
git checkout -f master
Git checkout (loosely) will update the working copy with the contents of the repository at the commit which specify. Your new_feature
branch doesn't have the second line which you've added to your file (since you haven't committed it yet). Right now, that extra line is just an untracked change in your working copy and it will get added to the branch on which you commit it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With