Git 常用命令与避坑指南
📅 2026/7/29 3:21:12
👁️ 阅读次数
📝 编程学习
Git 常用命令与避坑指南
一、Git 基础配置
# 设置全局用户信息(必填,否则无法提交)gitconfig--globaluser.name"你的用户名"gitconfig--globaluser.email"你的邮箱@example.com"# 设置默认分支名(可选)gitconfig--globalinit.defaultBranch main# 查看配置gitconfig--list二、Git 常用命令速查表
| 场景 | 命令 |
|---|---|
| 初始化仓库 | git init |
| 克隆远程仓库 | git clone <url> |
| 查看状态 | git status |
| 添加文件到暂存区 | git add <file>/git add . |
| 提交代码 | git commit -m "提交信息" |
| 推送到远程 | git push origin <branch> |
| 拉取远程更新 | git pull origin <branch> |
| 查看提交日志 | git log --oneline |
| 创建分支 | git branch <branch> |
| 切换分支 | git checkout <branch>/git switch <branch> |
| 合并分支 | git merge <branch> |
| 暂存工作区 | git stash |
| 恢复暂存 | git stash pop |
三、GitHub / Gitee 上传避坑指南
坑 1:远程仓库已有内容,本地推不上去
问题:git push被拒绝,提示failed to push some refs
原因:远程仓库初始化时创建了 README/LICENSE 等文件,本地没有这些文件
解决:
# 方法一:先拉取合并(推荐)gitpull origin main --allow-unrelated-historiesgitpush origin main# 方法二:强制推送(⚠️ 会覆盖远程)gitpush-uorigin main-f坑 2:push 时提示输入用户名密码
问题:每次 push 都要输入账号密码
解决:配置凭据缓存
# 缓存 15 分钟gitconfig--globalcredential.helper cache# 永久存储(Windows)gitconfig--globalcredential.helper store坑 3:SSH 推送报错Permission denied
问题:使用 SSH 方式推送报权限错误
解决:
# 1. 生成 SSH 密钥ssh-keygen-ted25519-C"你的邮箱@example.com"# 2. 查看公钥cat~/.ssh/id_ed25519.pub# 3. 将公钥添加到 GitHub/Gitee 的 SSH Keys 设置中# 4. 测试连接# GitHubssh-Tgit@github.com# Giteessh-Tgit@gitee.com坑 4:文件过大无法推送
问题:remote: error: File xxx is 100.00 MB; this exceeds the file size limit
解决:
# 安装 Git LFSgitlfsinstall# 追踪大文件gitlfs track"*.psd"gitlfs track"*.zip"# 然后正常 add/commit/push坑 5:误提交了敏感信息
问题:密码、密钥等被提交到仓库
紧急处理:
# 1. 立即修改泄露的密码/密钥!# 2. 从 Git 历史中移除文件gitfilter-branch--force--index-filter\"git rm --cached --ignore-unmatch 敏感文件路径"\--prune-empty --tag-name-filtercat----all# 3. 推送清理后的历史gitpush origin main--force--all# 4. 添加 .gitignore 防止再次提交echo"敏感文件名">>.gitignore坑 6:push 时提示detached HEAD
问题:不在任何分支上,无法 push
解决:
# 切换回主分支gitcheckout main# 或创建新分支保存当前修改gitcheckout-bnew-branch坑 7:GitHub 访问慢 / 连不上
解决:
# 使用 GitHub 镜像加速(临时)gitconfig--globalurl."https://ghproxy.com/https://github.com/".insteadOf"https://github.com/"# 或修改 hosts 文件绑定 IP# Gitee 一般无需加速四、推荐工作流
# 1. 克隆远程仓库gitclone git@github.com:用户名/仓库名.git# 2. 创建功能分支gitcheckout-bfeature/my-new-feature# 3. 开发并提交gitadd.gitcommit-m"feat: 添加新功能描述"# 4. 推送分支到远程gitpush-uorigin feature/my-new-feature# 5. 在 GitHub/Gitee 上创建 Pull Request / Merge Request五、Git 提交规范(推荐)
feat: 新功能 fix: 修复 bug docs: 文档更新 style: 代码格式(不影响逻辑) refactor: 重构 test: 测试相关 chore: 构建/工具变动示例:
gitcommit-m"feat: 添加用户登录功能"gitcommit-m"fix: 修复首页加载超时问题"提示:收藏本文档,遇到 Git 问题随时查阅 🎯
编程学习
技术分享
实战经验