加载中...
不想等待可以点我关掉

命令

查看历史与差异

1
2
3
4
5
6
7
git log               # 查看提交历史
git log --oneline # 简洁日志
git log --graph # 分支图
git show <commit> # 查看某次提交详情

git diff # 工作区 vs 暂存区
git diff --staged # 暂存区 vs 上一次提交

分支操作

1
2
3
4
5
6
7
8
9
10
11
git branch            # 查看本地分支
git branch -a # 查看所有分支(含远程)

git branch <name> # 创建分支
git checkout <name> # 切换分支(旧方式)
git switch <name> # 切换分支(推荐)

git checkout -b <n> # 创建并切换
git switch -c <n> # 创建并切换(新)

git branch -d <name> # 删除分支

合并 & 变基

1
2
git merge <branch>    # 合并分支
git rebase <branch> # 变基(线性历史)

远程仓库

1
2
3
4
5
6
7
8
9
git remote -v         # 查看远程仓库
git remote add origin <url>

git fetch # 拉取远程更新(不合并)
git pull # fetch + merge
git push # 推送到远程

git push origin main
git push -u origin main # 设定默认上游分支

查看 / 修改 URL

1
2
git remote get-url origin
git remote set-url origin git@github.com:xxx/yyy.git

上游仓库

1
2
3
4
5
6
7
8
9
10
11
# 1. Add upstream remote (only once)
git remote add upstream https://github.com/original/repo.git
git remote -v
# 2. Fetch latest changes from upstream
git fetch upstream
# 3. Switch to the branch you want to update
git checkout master
# 4. Merge upstream changes into your branch
git merge upstream/master
# 5. Push updates to your fork
git push origin master

撤销 & 回退

回退提交

1
2
3
git reset --soft HEAD~1   # 只撤销 commit
git reset --mixed HEAD~1 # 撤销 commit + add(默认)
git reset --hard HEAD~1 # 全部撤销(不可恢复)

安全回退

1
git revert <commit>

标签

1
2
3
4
git tag                 # 查看标签
git tag v1.0.0 # 创建标签
git tag -a v1.0 -m "v1"
git push origin --tags

配置相关

配置用户名和邮箱

1
2
3
4
git config --global user.name "Your Name"
git config --global user.email "xx@xx.com"

git config --list

设置代理

设置 HTTP 和 HTTPS 代理

1
2
git config --global http.proxy http://127.0.0.1:8080
git config --global https.proxy http://127.0.0.1:8080

如果代理需要用户名和密码验证:

1
2
git config --global http.proxy http://username:password@127.0.0.1:8080
git config --global https.proxy https://username:password@127.0.0.1:8080

取消代理

1
2
git config --global --unset http.proxy
git config --global --unset https.proxy

用SSH密钥对commit签名

1
2
3
git config commit.gpgsign true           # 设置commit时使用gpg签名
git config gpg.format ssh # 设置使用ssh密钥进行签名
git config user.signingkey <ssh私钥路径> # 配置ssh私钥路径

报错类

报错:error: You have not concluded your merge (MERGE_HEAD exists).

$

无权限写入组织仓库(GitHub)

  1. 完成组织权限设置

    Snipaste_2024-07-13_08-25-06
    Snipaste_2024-07-13_08-25-06
  2. 新建一个New fine-grained personal access tokenResource owner选择组织,权限处给予contents的读写权限

  3. 如果组织权限设置中开启了批准,则需回去在Pending requests里面启用

  4. 在本地仓库中运行:

git remote set-url origin https://{token}@github.com/{user}/{repo}.git

参考资料

  1. Git基础 - git tag 一文真正的搞懂git标签的使用