修改上一次的commit信息,

1
git commit --amend -m "some message"

强推

1
git push -f

情况:我在A分支commit了一些修改,我想在B分支做同样的更改:

1
2
3
4
# 查看 commit hash
git log --oneline
# 在 B 分支执行
git cherry-pick <commit hash>

丢弃工作区修改:

  • 未提交到暂存区的

    1
    2
    git restore file1 file2
    git restore .
  • 已经 add 到暂存区的

    1
    2
    3
    git restore --staged file1 file2
    git restore --staged .
    # 此时修改从暂存区回退到工作区,如果想丢弃工作区改动,参考上面的命令

git status发现文件名是\数字这种形式,原因是git将非ASCII编码的字符转义了(汉字是utf-8编码),解决办法(当前仓库生效,并不是全局生效):

1
git config core.quotepath false

初始化克隆子模块:

1
git submodule update --init --recursive

合并多个commit:

1
2
3
4
5
6
7
8
9
10
11
# 撤销 commit_sha 之后的提交,保留修改到工作区
git reset --soft commit_sha

# 回退到最近一次的commit,丢弃所有更改
git reset --hard

# 合并为一个提交
git commit -m ""

# 强推
git push -f

情况:当前在A分支写代码,需要切换到B分支,直接checkout会报错,而且A中代码还没写完不想commit:

1
2
3
4
5
6
7
8
9
10
11
# 暂存修改,此时工作区变动将被暂存,可以切换分支
git stash

# stash不会暂存未跟踪的文件,也就是如果新建的文件暂存不了,需要加 -u 参数
git stash -u

# 拿出更改,并删除该暂存
git stash pop

# 拿出更改,保留该暂存,适合想将暂存应用到多个分支
git stash apply

删除已经追踪的文件:

1
git rm -r --cached <path>

删除远程分支:

1
git push origin --delete test_memory_leak_py

设置分支上游:

1
git push -u origin <分支名>

作用:将origin <分支名>设置为当前分支的上游,以直接使用git push

把一个文件改炸了想恢复到head(但是更推荐用restore):

1
git checkout 文件名

git rebase

原来:

1
2
3
main:    A---B---C---D
\
feature: E---F---G

你执行:

1
2
git checkout feature
git rebase main

变成:

1
2
3
main:    A---B---C---D
\
feature: E'--F'--G'

E' F' G' 内容相同,但因为“重新贴上去”,所以 commit hash 变了。

提交历史线性干净,不会产生一个合并提交

想删除一串提交中的某一笔提交:

1
2
git log --oneline
git rebase -i hash # hash为要删除的那笔提交的前一个提交的hash

把要删除的那笔提交直接删除,或者将pick改为drop,ctrl+R然后y然后enter,强推到远端,完成。

不小心git add .了。如何撤销:

1
git restore --staged .

情况:将一些文件推送到了远端想撤销:

1
2
3
git rm --cached p1_by_rule.json    # 从暂存区移除,本地文件保留
git commit --amend --no-edit # 修改上一个提交
git push -f origin dev # 强推