Git 常用命令与避坑指南

发布时间:2026/7/29 3:03:52
Git 常用命令与避坑指南 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坑 2push 时提示输入用户名密码问题每次 push 都要输入账号密码解决配置凭据缓存# 缓存 15 分钟gitconfig--globalcredential.helper cache# 永久存储Windowsgitconfig--globalcredential.helper store坑 3SSH 推送报错Permission denied问题使用 SSH 方式推送报权限错误解决# 1. 生成 SSH 密钥ssh-keygen-ted25519-C你的邮箱example.com# 2. 查看公钥cat~/.ssh/id_ed25519.pub# 3. 将公钥添加到 GitHub/Gitee 的 SSH Keys 设置中# 4. 测试连接# GitHubssh-Tgitgithub.com# Giteessh-Tgitgitee.com坑 4文件过大无法推送问题remote: error: File xxx is 100.00 MB; this exceeds the file size limit解决# 安装 Git LFSgitlfsinstall# 追踪大文件gitlfs track*.psdgitlfs 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坑 6push 时提示detached HEAD问题不在任何分支上无法 push解决# 切换回主分支gitcheckout main# 或创建新分支保存当前修改gitcheckout-bnew-branch坑 7GitHub 访问慢 / 连不上解决# 使用 GitHub 镜像加速临时gitconfig--globalurl.https://ghproxy.com/https://github.com/.insteadOfhttps://github.com/# 或修改 hosts 文件绑定 IP# Gitee 一般无需加速四、推荐工作流# 1. 克隆远程仓库gitclone gitgithub.com:用户名/仓库名.git# 2. 创建功能分支gitcheckout-bfeature/my-new-feature# 3. 开发并提交gitadd.gitcommit-mfeat: 添加新功能描述# 4. 推送分支到远程gitpush-uorigin feature/my-new-feature# 5. 在 GitHub/Gitee 上创建 Pull Request / Merge Request五、Git 提交规范推荐feat: 新功能 fix: 修复 bug docs: 文档更新 style: 代码格式不影响逻辑 refactor: 重构 test: 测试相关 chore: 构建/工具变动示例gitcommit-mfeat: 添加用户登录功能gitcommit-mfix: 修复首页加载超时问题提示收藏本文档遇到 Git 问题随时查阅