抱歉,您的浏览器无法访问本站
本页面需要浏览器支持(启用)JavaScript
了解详情 >

Git 使用记录

按使用频率排序,越靠前越常用。先学会第一章就能干活,后面的遇到再查。

一、每天都在用

初始化

git config --global user.name "你的名字"
git config --global user.email "你的邮箱"

clone

git clone <仓库地址>
git clone --depth=1 <仓库地址> # 只拉最新版本,不要历史,大仓库快很多
git clone --recursive <仓库地址> # 连子模块一起拉

配置 SSH

ssh-keygen -t ed25519 -C "你的邮箱"   # 一路回车
cat ~/.ssh/id_ed25519.pub # 复制输出内容

粘贴到 GitHub 的 Settings → SSH and GPG keys,然后测试:

ssh -T git@github.com   # 看到 Hi xxx! 就成功了

之后用 git@github.com:xxx/xxx.git 格式的地址克隆,克隆和推送都会比基于http的方式更方便。

已有http仓库切换成 SSH:

git remote set-url origin git@github.com:xxx/xxx.git

提交与推送

git status                  # 看看改了哪些文件
git diff # 看看具体改了什么
git add . # 把所有改动加入暂存
git commit -m "说明改了什么" # 提交到本地,message是必须的
git push # 推送到远程

同步

git pull

查看历史

git log --oneline           # 一行一个提交
git log --oneline --graph # 带分支图
git show <commit> # 看某次提交改了什么

<commit> 指提交的哈希值,复制前 7 位就够了,如 8e8bd4a

二、分支

git branch                  # 查看本地分支
git branch -a # 查看所有分支(含远程)
git switch <分支名> # 切换分支
git switch -c <新分支名> # 新建并切换
git switch - # 切回上一个分支
git branch -d <分支名> # 删除分支
git push -u origin <分支名> # 第一次推送新分支

合并分支

把 feature 合进 main:

git switch main
git merge feature

解决冲突

合并时如果两边改了同一处,会出现冲突,文件里会出现这样的标记:

<<<<<<< HEAD
你的代码
=======
别人的代码
>>>>>>> feature

手动改成想要的样子,删掉标记,然后:

git add .
git commit

不想合了:git merge --abort

三、撤销

任务 命令
丢掉某个文件的修改 git restore <文件>
取消 git add git restore --staged <文件>
改上一次的提交信息 / 补个文件 git commit --amend
撤销上次提交,代码保留 git reset HEAD~1
撤销上次提交,代码也不要了 git reset --hard HEAD~1
撤销一个已经 push 的提交 git revert <commit>

已经 push 的提交,用 revert,不要用 reset 和 amend,否则会影响别人

误操作救命:reflog

reset --hard 后悔了、分支误删了,只要之前 commit 过,都能找回:

git reflog                  # 找到误操作前的那一行,如 HEAD@{1}
git reset --hard HEAD@{1} # 回到那个状态

四、暂存

代码写一半,要切分支去修 Bug:

git stash                   # 先把改动藏起来
# ...切分支、修 Bug、切回来...
git stash pop # 再拿回来
git stash list              # 查看藏了哪些
git stash -u # 连新建的文件一起藏

五、经常用

.gitignore

在项目目录建 .gitignore,写入不想提交的文件:

# 忽略 build 文件夹
build/
# 忽略所有 .log 文件
*.log
# 忽略任意位置的 __pycache__
**/__pycache__
# 例外:不忽略 keep.log
!keep.log

文件已经提交过了,再写进 .gitignore 是无效的,需要先移出 Git(本地文件不会删):

git rm -r --cached <文件或文件夹>

Cherry pick

把别的分支上的某个提交复制到当前分支:

git cherry-pick <commit>
git cherry-pick <开始commit>^..<结束commit> # 拿一段连续的提交

别名

能少打几个字

git config --global alias.s status
git config --global alias.c commit
git config --global alias.lg "log --oneline --graph --all"

之后 git s 就等于 git status。

rebase

拉取时不产生多余的合并提交

git pull --rebase
# 或者设为默认
git config --global pull.rebase true

合并多个提交:rebase -i

push 之前,把本地零碎的几个提交合成一个:

git rebase -i HEAD~3        # 整理最近 3 个提交

在弹出的编辑器中,把要合并的提交前面的 pick 改成 s(squash),保存退出即可。

只对还没 push 的提交这么做

强制推送

不推荐使用

改写了历史(amend、rebase)后,普通 push 会被拒绝,用:

git push --force-with-lease

比 --force 安全:如果别人在这期间推送过,它会拒绝,不会把别人的代码冲掉。

tag

标记版本

git tag v1.0.0              # 打标签
git push origin --tags # 推送标签(默认不会随 push 推送)
git tag --sort=creatordate # 按时间列出标签
git switch -c mybranch v1.0.0 # 基于某个标签建分支

六、偶尔用

blame

这个功能其实网页端用的比较多,查某个文件被谁改过

git blame <文件>
git blame -L 10,20 <文件> # 只看第 10-20 行

查代码是什么时候删的

git log -S "某段代码"

bisect

基于二分查找,查哪个提交引入了 Bug,几百个提交也只需要测几次:

git bisect start
git bisect bad # 当前版本有 Bug
git bisect good <commit> # 这个旧版本没 Bug
# Git 会自动切到中间的版本,测试后告诉它结果:
git bisect good # 或 git bisect bad
# ...重复直到找到问题提交
git bisect reset # 结束

补丁

在没有关联的仓库之间搬代码

# 导出最近 1 个提交为补丁文件(保留提交信息)
git format-patch -1
# 在另一个仓库应用,自动生成提交
git am 0001-xxx.patch

只要代码差异、不要提交信息:

git diff branch1 branch2 > my.patch
git apply my.patch
git apply --reject my.patch # 有冲突时生成 .rej 文件,手动处理

子模块

我非常喜欢submodule,可以让主仓库的提交相对整洁

git submodule add <仓库地址> <路径>       # 添加
git clone --recursive <仓库地址> # 克隆时一起拉子模块
git submodule update --init --recursive # 已克隆的项目补拉子模块

LFS

模型、视频、压缩包等二进制大文件直接提交会让仓库越来越大,交给 LFS 管理:

brew install git-lfs        # macOS;Ubuntu 用 sudo apt-get install git-lfs
git lfs install
git lfs track "*.zip"
git add .gitattributes # track 规则存在这个文件里,要提交

worktree

同时开发两个分支,不需要 stash,也不用再 clone 一份:

git worktree add ../hotfix hotfix   # 在 ../hotfix 目录打开 hotfix 分支
git worktree remove ../hotfix # 用完删掉

清理

git clean -nd               # 预览会删除哪些未跟踪的文件
git clean -fd # 真的删除
git gc # 压缩仓库,释放空间

七、环境问题

连不上 GitHub(443 报错)

fatal: unable to access ‘https://github.com/…’: Failed to connect to github.com port 443

开着梯子还是连不上,给 Git 设置代理(端口换成你自己梯子的):

git config --global http.proxy http://127.0.0.1:7890
git config --global https.proxy http://127.0.0.1:7890
# 取消
git config --global --unset http.proxy
git config --global --unset https.proxy

移动项目后,所有文件都显示被修改

权限变了,内容其实没变:

git config core.fileMode false

报错 dubious ownership

git config --global --add safe.directory <仓库路径>

中文文件名显示成 \346\226\207

git config --global core.quotepath false

八、GitHub Webhook

它能干嘛

仓库发生某件事(比如有人 push)时,GitHub 自动给你的服务器发一个 HTTP 请求。

最常见的用法:push 后自动更新服务器上的网站。

第一步:在 GitHub 上配置

仓库页面 → Settings → Webhooks → Add webhook,填写:

选项 填什么
Payload URL 你服务器接收请求的地址,如 https://example.com/webhook
Content type application/json
Secret 随便一串密码,用来确认请求真的来自 GitHub
事件 选 Just the push event

保存后 GitHub 会先发一个 ping 请求测试连通性。

第二步:在服务器上接收

用 Python 写一个最简单的接收服务(需要 pip install flask):

# webhook.py
import hashlib, hmac, subprocess
from flask import Flask, request, abort

app = Flask(__name__)
SECRET = b"你填的Secret"
REPO_DIR = "/srv/blog" # 服务器上的项目目录

@app.post("/webhook")
def webhook():
# 校验请求是否来自 GitHub,防止别人伪造请求
sign = "sha256=" + hmac.new(SECRET, request.get_data(), hashlib.sha256).hexdigest()
if not hmac.compare_digest(sign, request.headers.get("X-Hub-Signature-256", "")):
abort(401)

# 只处理 main 分支的 push
if request.headers.get("X-GitHub-Event") == "push" \
and request.json.get("ref") == "refs/heads/main":
# 后台拉取最新代码,不等它执行完就返回(GitHub 10 秒收不到响应算失败)
subprocess.Popen(["git", "pull"], cwd=REPO_DIR)

return "ok"

app.run(host="0.0.0.0", port=5000)
python webhook.py

想在拉代码后再执行构建、重启服务,把 git pull 换成你自己的部署脚本即可,如 ["bash", "deploy.sh"]。

本地测试

本地电脑没有公网地址,GitHub 访问不到,可以用 smee.io 转发:

  1. 打开 smee.io,点 Start a new channel,得到一个地址
  2. 把这个地址填到 GitHub 的 Payload URL
  3. 本地运行:
npx smee-client --url https://smee.io/你的地址 --target http://127.0.0.1:5000/webhook

出问题了怎么查

Webhook 设置页 → Recent Deliveries,能看到每次请求的内容和你服务器的返回结果。点 Redeliver 可以重发,不用反复 push 来测试。

注意

  • 一定要设置 Secret 并校验,否则谁都能触发你的部署
  • Secret 不要提交到仓库里,正式使用时放到环境变量中
  • 只是想 push 后跑测试、打包,用 GitHub Actions 更简单;Webhook 适合通知你自己的服务器

评论