问题描述
我有一个家庭作业,我需要对同一个程序进行三种不同的植入。这位教授建议使用GIT,并在不同的分支上进行植入。问题是,当我在名为A的分支上进行更改时,它也会修改主分支中的相同文件……我不希望它将我的更改带到每个分支,而是将更改单独保存在每个分支上。我该怎么做?
(我刚开始使用Git) (我们在终端上的远程服务器Linux上工作)
编辑:我用来创建项目目录的命令:
git init
git commit -m "my message"
git checkout // to switch branches
git branch branchname // to create a branch
推荐答案
当我这样做时:
$ git init
Initialized empty Git repository in MyPath/Test1/.git/
然后我创建了一个文件test.txt
$ touch test.txt
$ git add test.txt
$ git commit -m " commit 1 "
现在我想在另一个分支中修改它
$ git checkout -b branch1
$ echo "Branch 1" >> test.txt
这里是棘手的部分...
如果我不使用git add test.txt
添加文件,并且我不提交,而是直接备份到master:
$ git checkout master
Switched to branch 'master'
M test.txt
我将在master
中看到修改!!:
$ git status
On branch master
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git restore <file>..." to discard changes in working directory)
modified: test.txt
我应该做的是在分支1中add
和commit
:
$ git checkout branch1
$ git add test.txt
$ git commit -m "commit from branch 1"
[branch1 1b562f5] commit from branch 1
1 file changed, 1 insertion(+)
$ git log
commit 1b562f5be40a50df04f8a2a15b58a7af61742275 (HEAD -> branch1)
Author: xxxxxx<xxxxx.xxxx.xxx@xxxx.com>
Date: Thu Jun 3 16:36:30 2021 +0200
commit from branch 1
commit 03684e2a02c1a37a8f4546f296c6802686c7a4e9 (master)
Author: xxxx<xxx.xx.xx@xxxx.com>
Date: Thu Jun 3 16:31:05 2021 +0200
commit 1
如果我返回master
并检查日志:
$ git checkout master
Switched to branch 'master'
$ git log
commit 03684e2a02c1a37a8f4546f296c6802686c7a4e9 (HEAD -> master)
Author: xxxxx<xxxxx.xxxx.xxxxx@xxxx.com>
Date: Thu Jun 3 16:31:05 2021 +0200
commit 1
我们不会看到修改...不出所料
所以!如果即使您尚未完成当前分支,也希望在其他分支上工作,该怎么办?
我返回到分支1并cat
其内容
$ git checkout branch1
Switched to branch 'branch1'
$ cat test.txt
Branch 1
继续编辑
$ echo "Branch 1..1" >> test.txt
让add
而不是commit
尝试checkout
掌握
$ git add test.txt
$ git checkout master
error: Your local changes to the following files would be overwritten by checkout:
test.txt
Please commit your changes or stash them before you switch branches.
Aborting
不可能!你必须先commit
,但是!您不希望每次更改分支时都有新的提交,因此您只需commit --amend
$ git commit --amend
$ git log
commit 40a3a66e2b45a253f9a6ed564e977887c0748bf0 (HEAD -> branch1)
Author: xxxxx<xxxxx.xxxxx.xxxxx@xxxxx.com>
Date: Thu Jun 3 16:36:30 2021 +0200
commit from branch 1 => I can edit the comment!!
commit 03684e2a02c1a37a8f4546f296c6802686c7a4e9 (master)
Author: xxxxx<xxxxx.xxxxx.xxxxx@xxxxx.com>
Date: Thu Jun 3 16:31:05 2021 +0200
commit 1
现在我可以安全地git checkout master