git reset和revert的区别

113 阅读1分钟

是用于撤销回滚提交的两个操作。使用 git reset 回滚后历史记录会被更改,需要用 git push -f 强制推送到远程分支,谨慎使用;git revert 则是创建新的提交,历史记录保留。

git reset 有以下几种模式:常用 --mixed(默认,指定的 commit-hash 之后提交保留到工作区), --soft(指定的 commit-hash 之后提交保留到暂存区,工作区不变), --hard(指定的 commit-hash 之后提交都移除不保留)

错误使用了 git reset --hard ,可以使用 git reflog 找到要回滚的提交记录hash,重新使用git reset命令进行回滚。

git 的 reflog 不是一个持久的日志记录系统(Git不会限制reflog的大小,它会不断增长,直到你的存储空间耗尽),可以通过 git reflog expire 命令设置过期规则。

git reset -h
usage: git reset [--mixed | --soft | --hard | --merge | --keep] [-q] [<commit>]
   or: git reset [-q] [<tree-ish>] [--] <pathspec>...
   or: git reset [-q] [--pathspec-from-file [--pathspec-file-nul]] [<tree-ish>]
   or: git reset --patch [<tree-ish>] [--] [<pathspec>...]
   or: DEPRECATED: git reset [-q] [--stdin [-z]] [<tree-ish>]

    -q, --quiet           be quiet, only report errors
    --mixed               reset HEAD and index
    --soft                reset only HEAD
    --hard                reset HEAD, index and working tree
    --merge               reset HEAD, index and working tree
    --keep                reset HEAD but keep local changes
    --recurse-submodules[=<reset>]
                          control recursive updating of submodules
    -p, --patch           select hunks interactively
    -N, --intent-to-add   record only the fact that removed paths will be added later
    --pathspec-from-file <file>
                          read pathspec from file
    --pathspec-file-nul   with --pathspec-from-file, pathspec elements are separated with NUL character
    -z                    DEPRECATED (use --pathspec-file-nul instead): paths are separated with NUL character
    --stdin               DEPRECATED (use --pathspec-from-file=- instead): read paths from <stdin>

image.png

# 设置reflog过期时间为7天
git reflog expire --expire=7
 
# 删除所有过期的reflog条目
git reflog expire --all
 
# 手动运行垃圾收集以清理过期的reflog条目
git gc