1. 初始化与克隆
git init
初始化一个新的本地仓库。git clone <repo-url>
克隆远程仓库到本地(如git clone https://github.com/user/repo.git
)。
2. 基础操作
git add <file>
将文件添加到暂存区(如git add main.py
)。git add .
或git add -A
:添加所有变更文件。
git commit -m "提交信息"
提交暂存区的变更到本地仓库。git commit -am "提交信息"
:直接提交已跟踪文件的修改(无需add
)。
git status
查看工作区和暂存区的状态。git diff
查看未暂存的变更内容。git diff --cached
:查看已暂存的变更。
3. 分支管理
git branch
列出所有本地分支(-a
查看所有分支,包括远程)。git branch <branch-name>
创建新分支。git checkout <branch-name>
切换到指定分支。git checkout -b <branch-name>
:创建并切换到新分支(等效于git switch -c
)。
git merge <branch-name>
将指定分支合并到当前分支。git rebase <branch-name>
变基操作(将当前分支的提交移到目标分支的顶部)。git branch -d <branch-name>
删除本地分支(-D
强制删除未合并的分支)。
4. 远程仓库操作
git remote -v
查看远程仓库地址。git remote add <name> <url>
添加远程仓库(如git remote add origin https://github.com/user/repo.git
)。git push <remote> <branch>
推送本地分支到远程仓库(如git push origin main
)。git push -u origin main
:首次推送时设置上游分支。git push --force
:强制推送(谨慎使用)。
git pull <remote> <branch>
拉取远程分支并合并(等效于git fetch
+git merge
)。git pull --rebase
:拉取时使用变基而非合并。
git fetch <remote>
下载远程仓库的变更,但不合并。
5. 撤销与回退
git restore <file>
撤销工作区的修改(未add
的变更)。git reset <file>
将文件移出暂存区(保留工作区修改)。git reset --hard HEAD
:丢弃所有未提交的变更(慎用!)。git reset --hard <commit-id>
:回退到指定提交(会丢失之后的提交)。
git revert <commit-id>
创建一个新提交来撤销指定提交(安全回退方式)。
6. 日志与历史
git log
查看提交历史。git log --oneline
:简洁模式。git log --graph
:图形化显示分支。
git show <commit-id>
查看某次提交的详细信息。git blame <file>
查看文件的修改记录(按行显示作者)。
7. 暂存临时工作
git stash
临时保存未提交的变更。git stash pop
:恢复最近暂存的变更。git stash list
:查看所有暂存记录。
8. 标签管理
git tag
列出所有标签。git tag -a v1.0 -m "版本说明"
创建附注标签。git push origin --tags
推送所有标签到远程仓库。
9. 配置相关
git config --global user.name "姓名"
设置全局用户名。git config --global user.email "邮箱"
设置全局邮箱。git config --list
查看当前配置。
常用场景示例
首次推送本地项目到远程仓库
git init git add . git commit -m "Initial commit" git remote add origin <repo-url> git push -u origin main
修复提交信息
git commit --amend -m "新的提交信息"
合并分支并解决冲突
git checkout main git merge feature-branch # 手动解决冲突后 git add . git commit
掌握这些命令可以应对 90% 的日常 Git 操作。更复杂的用法(如 rebase -i
、子模块等)可查阅 Git 官方文档。