本文将介绍如何在各个平台安装 Git,并整理了日常开发中最常用的 Git 管理命令。
1. Git 的安装
Windows
前往 Git 官方下载页面,下载 .exe 安装包,一路点击 “Next” 默认安装即可。
macOS
打开终端,使用 Homebrew 安装:
Linux (Ubuntu/Debian)
1 2
| sudo apt update sudo apt install git
|
2. 测试是否安装成功
安装完成后,打开终端(Windows 用户可打开 Git Bash 或 PowerShell),输入以下命令测试:
期望输出:git version 2.4x.x (只要能打印出版号,说明安装成功!)
3. 初次运行配置
安装成功后,必须先配置你的用户名和邮箱,这会作为你提交代码的身份凭证:
1 2
| git config --global user.name "你的名字" git config --global user.email "你的邮箱@example.com"
|
检查配置是否生效:
4. Git 常用命令速查
仓库初始化与克隆
git init:在当前目录初始化一个全新的 Git 仓库。
git clone <url>:克隆远程仓库到本地。
代码提交与暂存
git status:查看当前工作区文件的状态。
git add .:将所有修改的文件放入暂存区。
git commit -m "提交说明":将暂存区的内容提交到本地仓库。
分支管理
git branch:列出所有本地分支。
git checkout -b <branch_name>:创建并切换到一个新分支。
git merge <branch_name>:将指定分支合并到当前分支。
远程同步
git push origin main:将本地 main 分支推送到远程仓库。
git pull origin main:从远程仓库拉取最新的代码并合并。
git fetch:拉取远程仓库的更新,但不自动合并。
git remote -v:查看远程仓库地址。
git remote add origin <url>:关联远程仓库。
5. 查看历史版本
git log — 查看提交历史
1 2 3 4 5 6 7
| git log git log --oneline git log --oneline -10 git log --graph --oneline git log -p git log --author="名字" git log --since="2026-01-01" --until="2026-06-01"
|
git show — 查看某次提交的详情
1 2 3
| git show <commit_id> git show HEAD git show HEAD~1
|
git diff — 查看文件差异
1 2 3 4
| git diff git diff --staged git diff branch1 branch2 git diff <commit1> <commit2>
|
git blame — 逐行追溯
6. 版本回退
核心概念:HEAD 指向当前所在的版本。~ 表示往前几个版本,如 HEAD~3 就是往前 3 个版本。
git reset — 回退版本(修改历史)
1 2 3 4 5 6 7 8 9
| git reset --soft HEAD~1
git reset --mixed HEAD~1 git reset HEAD~1
git reset --hard HEAD~1
|
| 参数 |
commit |
暂存区 |
工作区 |
--soft |
撤销 |
保留 |
保留 |
--mixed |
撤销 |
撤销 |
保留 |
--hard |
撤销 |
撤销 |
撤销 |
git revert — 撤销某次提交(不修改历史)
1 2
| git revert <commit_id> git revert HEAD
|
revert 和 reset 的区别:revert 不会改变历史,适合已经推送到远程的提交;reset 会改写历史,适合本地还没推送的提交。
git checkout — 恢复文件
1 2
| git checkout -- <file> git checkout <commit_id> -- <file>
|
git stash — 临时保存工作区
1 2 3 4 5
| git stash git stash list git stash pop git stash apply git stash drop
|
7. 实用技巧
撤销已经 push 到远程的提交
1 2 3 4 5 6 7
| git revert <commit_id> git push origin main
git reset --hard <commit_id> git push origin main --force
|
查看某个文件的历史版本
1 2 3
| git log --oneline <file> git show <commit_id>:<file> git checkout <commit_id> -- <file>
|
修改最近一次 commit 的信息
查看分支图(推荐日常使用)
1
| git log --graph --oneline --all --decorate
|
8. 常见场景速查
| 场景 |
命令 |
| 丢弃未 add 的修改 |
git checkout -- <file> |
| 丢弃已 add 未 commit 的修改 |
git reset HEAD <file> |
| 回退到上一个版本 |
git reset --hard HEAD~1 |
| 撤销某次提交(已 push) |
git revert <commit_id> |
| 暂存当前工作 |
git stash |
| 查看简要日志 |
git log --oneline -10 |
| 对比两个分支 |
git diff branch1 branch2 |
| 查看文件谁改的 |
git blame <file> |