Files
OneMD/posts/blog/效率与工具/工具/git/git基本命令.md
T
2026-06-19 14:45:07 +08:00

176 lines
3.2 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
---
title: git基本命令
date: 2024-12-10
tags: [git]
---
## 基本操作
1、初始化:`git init`
2、添加(全部文件到)暂存区:`git add .`
- 相当于交给git管理文件
撤销暂存区:`git reset`
3、添加到本地仓库:`git commit -m 'msg'`
4、添加到远程仓库:`git push -u origin "master"`
- 前提是添加了远程仓库,如下
`git remote add origin` `[https://gitee.com/QGS_Code/file-system.git](https://gitee.com/QGS_Code/file-system.git)`
取消git管理
- 删除.git
更换远程仓库
- git remote -v
- git remote set-url origin [https://github.com/yourusername/new-repository.git](https://github.com/yourusername/new-repository.git)
### 可以设置 `git status` 忽略未关心目录里的改动
比如前端不关心 backend 改动,可以临时忽略:
```Shell
git update-index --assume-unchanged backend/*
```
恢复:
```Shell
git update-index --no-assume-unchanged backend/*
```
反过来一样。
---
git版本控制
本地记录
- master分支:A — B — C
- 其他分支:A — B — C — D — E
远程记录
- 远程masterA— B — C
- 其他远程分支:A — B — C — D — E
### git fetch
这会更新本地的**远程跟踪分支**
### git **merge** master
把master的内容**合并**到当前分支,生成一个新版本,一般都是将其他分支合(新功能)并到主分支
- 图解
👉 `M` 是 merge commit,表示 `comment_dev``master` 的 C 合进来了。
```Java
A---B---C (master)
\
D---E (comment_dev)
A---B---C (master)
\ \
D---E---M (comment_dev)
更新内容
A---B---C (master)
\
D---E (comment_dev)
A---B---C---M (master)
\ \
D---E (comment_dev)
```
### git pull
=**git fetch + git merge**
### git **rebase** master
基于最新版本开发(可能要解决冲突),**变基,**合并代码的另一种方式
- 将 `**comment_dev**` 的提交 `**D**` 和 `**E**` 暂存起来。
- 将 `**comment_dev**` 的指针移动到 `**master**` 的最新提交 `**G**`。
- 尝试将 `**D**` 和 `**E**` 重新应用到 `**G**` 之上。
```Java
A---B---C (master)
\
D---E (comment_dev)
A---B---C (master)
\
D---E (comment_dev)
```
## 📌 注意 ⚠️
- **rebase 之后必须强推(push -f**
因为提交历史改了,普通 push 会被拒绝。
```Shell
git push -f origin feature-branch
```
- 不要对**公共分支**(比如 dev、master)执行 rebase,会影响其他人。
### 本地 `master` 回退到你想要的版本
比如:
```Shell
git checkout master
git reset --hard 4e5f6g7 # 你要回去的那个 commit
```
---
### 📊 2️⃣ 强制推送覆盖远程 master
```Shell
git push -f origin master
```
查看提交记录(q 退出)
```Shell
git log --oneline --graph --decorate
```
## 📦 总结:
| | | | |
|---|---|---|---|
|操作|远程新提交|本地 `A`|本地 `origin/A`|
|`fetch`|获取到了|不变|更新到最新|
|`merge origin/A`|会合并|和 `origin/A` 合并|-|
|`pull`(默认 `fetch+merge`|获取并合并|会更新|同步|