git staging and committing between multiple branches

≯℡__Kan透↙ 提交于 2019-12-03 06:07:40
larsks

It doesn't matter what branch you're on when you add a file, only when you commit it. So if you do this:

git add file
git checkout master
git commit

You have committed the file to the master branch.

Here's a complete example, with output. We start with a new repository:

$ git init
Initialized empty Git repository in /home/lars/tmp/so/repo/.git/

At this point, we're on the master branch and we haven't yet added any files. Let's add a file:

$ date > file1
$ cat file1
Fri May 11 13:05:59 EDT 2012
$ git add file1
$ git commit -m 'added a file'
[master (root-commit) b0764b9] added a file
1 files changed, 1 insertions(+), 0 deletions(-)
create mode 100644 file1

Great, we now have a branch (master) with one commit. Let's create the new branch:

$ git checkout -b foo
Switched to a new branch 'foo'
$ git branch
* foo
  master
$ ls
file1

Now we'll add a line to file1.

$ date >> file1
$ git status
# On branch foo
# Changes not staged for commit:
#   (use "git add <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#
#       modified:   file1
#
no changes added to commit (use "git add" and/or "git commit -a")

This shows that the file has been modified, but not yet staged. Let's stage the file and commit it:

$ git add file1
$ git commit -m 'made a change'
[foo 761bed9] made a change
 1 files changed, 1 insertions(+), 0 deletions(-)

And re-run git status:

$ git status
# On branch foo
nothing to commit (working directory clean)

At this point, the file looks like this:

Fri May 11 13:05:59 EDT 2012
Fri May 11 13:07:36 EDT 2012

If we switch back to the master branch, we'll see the earlier version of the file without the second line:

$ git checkout master
Switched to branch 'master'
$ cat file1
Fri May 11 13:05:59 EDT 2012

Changes to a file are isolated to the branch on which they were committed.

In your updated example, this...

$ git checkout master

...does not generate an error because at this point, the version of 'one' in both master and fire is identical. The changes in the working directory would apply equally well to either version.

The staging area aka index is common to all branches, which explains your observation

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!