Git 入门学习笔记

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    # ❌ Notepad 会加 .txt 后缀
echo xxx > .gitignore # ❌ PowerShell 默认输出 UTF-16,Git 读不懂

检测是否生效

1
git check-ignore -v node_modules/xxx

有输出 ✅ 没输出 ❌

如果文件已被跟踪过

1
2
git rm -r --cached -f .   # 解除跟踪(不删硬盘文件)
git add . # 重新加,.gitignore 生效

五、.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
1
git add --renormalize .   # 按新规则重扫

六、回滚操作

情况 命令
改坏了没 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 隐藏文件看不到 资源管理器 → 查看 → 隐藏的项目

Git 入门学习笔记
https://blog.shinebook.net/2026/05/05/编程/Git学习笔记/
作者
X
发布于
2026年5月5日
许可协议