2026-05-05 第一次完整学 Git,记录全程知识点和踩坑经历。
一、核心概念
Git 是一个版本管理工具,核心流程:
1
| 工作目录 → git add → 暂存区 → git commit → 本地仓库 → git push → 远程仓库
|
二、常用命令速查
git init |
初始化仓库 |
git add . |
全部加入暂存区 |
git commit -m "备注" |
提交快照 |
git status |
看当前状态 |
git log --oneline |
看提交历史 |
三、配置(必备)
1 2
| git config --global user.name "你的名字" git config --global user.email "你的邮箱"
|
--global = 全局配置,配一次就不用再配
- 名字和邮箱会写进每次提交记录
- 如果用 GitHub,邮箱建议和 GitHub 注册邮箱一致
四、.gitignore — 排除垃圾文件
排除不该提交的文件(如 node_modules/ 等)。
PowerShell 创建(必须指定
UTF-8)
1 2 3 4 5 6
| @" node_modules/ tmp_* .DS_Store *.log "@ | Set-Content .gitignore -Encoding UTF8
|
不要这样做
1 2
| notepad .gitignore echo xxx > .gitignore
|
检测是否生效
1
| git check-ignore -v node_modules/xxx
|
有输出 ✅ 没输出 ❌
如果文件已被跟踪过
1 2
| git rm -r --cached -f . git add .
|
五、.gitattributes —
统一换行符
为什么需要: Win 用 CRLF,Linux 用 LF。Git
默认帮你转,会刷屏 LF→CRLF。
用 .gitattributes 精确声明(比关
core.autocrlf 专业):
1 2 3 4 5
| * text=auto *.js text eol=lf *.json text eol=lf *.md text eol=lf *.png binary
|
六、回滚操作
| 改坏了没 commit |
git checkout . |
| 刚 commit 想撤回 |
git reset --soft HEAD~1 |
| 放弃所有改动 |
git reset --hard HEAD~1 |
| 安全撤销某次提交 |
git revert 版本号 |
| 打标签标记版本 |
git tag v1.0 |
七、远程仓库
GitHub
1 2
| git remote add origin https://github.com/用户名/项目名.git git push -u origin main
|
阿里云(自建)
1 2 3 4 5 6 7
| ssh root@服务器IP mkdir -p /srv/git/项目名.git; cd $_; git init --bare
git remote add aliyun root@服务器IP:/srv/git/项目名.git git push aliyun main
|
八、今天踩坑速查
| 1 |
Notepad 自动加 .txt |
Win 隐藏扩展名 |
用 PowerShell |
| 2 |
.gitignore 没效果 |
PowerShell > 输出 UTF-16 |
Set-Content -Encoding UTF8 |
| 3 |
2>/dev/null 报错 |
PowerShell 不认 Linux 语法 |
用 2>$null |
| 4 |
LF→CRLF 刷屏 |
core.autocrlf=true |
加 .gitattributes |
| 5 |
Author identity unknown |
没配 name/email |
git config --global |
| 6 |
node_modules 还在跟踪 |
已跟踪的文件 .gitignore 管不了 |
先 git rm --cached |
| 7 |
check-ignore 没输出 |
core.excludesFile 干扰 |
--unset 删掉 |
| 8 |
staged content different |
文件在暂存区冲突 |
加 -f 强制 |
| 9 |
找不到 .gitignore |
隐藏文件看不到 |
资源管理器 → 查看 → 隐藏的项目 |