1. 撤销已暂存的文件
Git 的一些命令在修改文件状态的同时,也会提示如何撤消操作。
假如,已经修改了两个文件并且想要将它们分开作为两次修改来 commit 但是意外输入了 git add .
暂存了两个文件。
需要只撤销暂存两个中的一个。输入 git status
命令:
$ git status
On branch master
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
renamed: readme -> readme.md
modified: test.cpp
AI 代码解读
在 “Changes to be committed” 文字正下方,提示使用 git reset HEAD <file>
来取消暂存。 所以可以这样来取消暂存 test.cpp 文件:
$ git reset HEAD test.cpp Unstaged changes after reset: M test.cpp
AI 代码解读
再次查看状态,则看到
$ git status
On branch master
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
renamed: readme -> readme.md
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: test.cpp
AI 代码解读
test.cpp 文件已经是已修改未暂存的状态了。
注意:
git reset
很危险,尤其是使用 --hard 选项。使用时一定明确自己的操作,否则可能会丢失已做的工作和浪费了很多时间, 但此处并不修改工作目录中的文件。
2. 撤消对文件的修改
如果不想保留对 test.cpp 文件的修改,将它还原成上次提交时的样子。 同样的,git status
也告诉了我们应该如何做。 在前一个例子末尾这样提示
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: test.cpp
AI 代码解读
它非常清楚地告诉了我们应该如何撤消之前的修改
use "git checkout -- <file>..." to discard changes in working directory
AI 代码解读
需要执行
$ git checkout -- test.cpp
AI 代码解读
此时我们再次查看
$ git status
On branch master
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
renamed: readme -> readme.md
AI 代码解读
可以看到对 test.cpp 文件的修改已经被撤消了。
注意
同样的 git checkout -- <file>
也是一个危险的操作,所有对指定文件在本地的任何修改都会消失,Git 会用最近提交的版本覆盖掉它。
因此,除非特别确实清楚不想要对那个文件的本地修改了,否则请不要轻易使用这个命令。
如果你仍然想保留对那个文件做出的修改,但是现在仍然需要撤消,我们将会在 Git 分支 介绍保存进度与分支,这通常是更好的做法。
3. 从远程仓库拉取
从远程仓库中获得数据,可以执行:
$ git fetch <remote>
AI 代码解读
如果完整的,可以不需要添加 remote 信息。此命令访问远程仓库,从中拉取所有本地还没有的数据。 执行完成后,本地则会拥有远程仓库中所有分支的引用,可以随时合并或查看。
例:
git fetch origin
AI 代码解读
git fetch
命令只会将数据下载到你的本地仓库,但它并不会自动合并或修改你当前的工作。 必须手动将其合并入。
git pull 命令可以自动拉取后合并该远程分支到当前分支。
4. 推送到远程仓库
推送命令为:
git push <remote> <branch>
AI 代码解读
当需要将 master 分支推送到 origin 时
git push origin master
AI 代码解读