根据labuladong的算法小抄记录git容易忘记而工作又需要用到的命令 : add, commit, reset, checkout
一、前言
working directory、stage area、history区的关系:
再看看状态转移图:
二、工作常用需求
需求一:把work dir中的修改加入stage--->: git add a.txt 或者 git add .
$ touch a.txt b.txt
$ git add .
$ git status
On branch master
Changes to be committed:
new file: a.txt
new file: b.txt
需求二: 把stage中的修改还原到work directory中--->:git checkout a.tex 或 git checkout .
$ git checkout a.txt
Updated 1 path from the index
$ git status
On branch master
Changes to be committed:
new file: a.txt
new file: b.txt
需求三:将stage中的文件添加到history区---> git commit -m '一些描述'
如果最近的commit只是简单的修改,不想重开一个commit,可以使用 git commit --amend,将会合并最近的一个commit
需求四:将history区的文件还原到stage区--> git reset a.txt 或者git reset .
完整的命令如下:
$ git reset --mixed HEAD a.txt
其中,mixed
是一个模式(mode)参数,如果 reset
省略这个选项的话默认是 mixed
模式;HEAD
指定了一个历史提交的 hash 值;a.txt
指定了一个或者多个文件。
该命令的自然语言描述是:不改变 work dir
中的任何数据,将 stage
区域中的 a.txt
文件还原成 HEAD
指向的 commit history
中的样子。就相当于把对 a.txt
的修改从 stage
区撤销,但依然保存在 work dir
中,变为 unstage
的状态。
需求五:将work dir的修改提交到history区--> 先git add 再 git commit,或一部到位 git commit -a
需求六:将history区中的历史提交还原到work dir中--> git checkout 2bdf04a some_test.java
这样会将work dir和stage中所有的文件修改,恢复成哈希2bdf04a所指向的那个history commit
最后,可以使用 git reflog 命令查看操作记录。