Git之常用命令与避坑指南分享
更新时间:2026年07月30日 09:25:57 作者:落魄大学生之流水线上谋生计
还在为Git命令记不住而烦恼?本文汇总了Git基础配置、常用命令速查表,以及GitHub/Gitee上传的7大常见坑和解决方案,包括push被拒、SSH权限错误、文件过大等,同时分享推荐工作流和提交规范,助你轻松应对版本控制
一、Git 基础配置
# 设置全局用户信息(必填,否则无法提交) git config --global user.name "你的用户名" git config --global user.email "你的邮箱@example.com" # 设置默认分支名(可选) git config --global init.defaultBranch main # 查看配置 git config --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 等文件,本地没有这些文件
解决:
# 方法一:先拉取合并(推荐) git pull origin main --allow-unrelated-histories git push origin main # 方法二:强制推送(⚠️ 会覆盖远程) git push -u origin main -f
坑 2:push 时提示输入用户名密码
问题:每次 push 都要输入账号密码
解决:配置凭据缓存
# 缓存 15 分钟 git config --global credential.helper cache # 永久存储(Windows) git config --global credential.helper store
坑 3:SSH 推送报错Permission denied
问题:使用 SSH 方式推送报权限错误
解决:
# 1. 生成 SSH 密钥 ssh-keygen -t ed25519 -C "你的邮箱@example.com" # 2. 查看公钥 cat ~/.ssh/id_ed25519.pub # 3. 将公钥添加到 GitHub/Gitee 的 SSH Keys 设置中 # 4. 测试连接 # GitHub ssh -T git@github.com # Gitee ssh -T git@gitee.com
坑 4:文件过大无法推送
问题:
remote: error: File xxx is 100.00 MB; this exceeds the file size limit
解决:
# 安装 Git LFS git lfs install # 追踪大文件 git lfs track "*.psd" git lfs track "*.zip" # 然后正常 add/commit/push
坑 5:误提交了敏感信息
问题:密码、密钥等被提交到仓库
紧急处理:
# 1. 立即修改泄露的密码/密钥! # 2. 从 Git 历史中移除文件 git filter-branch --force --index-filter \ "git rm --cached --ignore-unmatch 敏感文件路径" \ --prune-empty --tag-name-filter cat -- --all # 3. 推送清理后的历史 git push origin main --force --all # 4. 添加 .gitignore 防止再次提交 echo "敏感文件名" >> .gitignore
坑 6:push 时提示detached HEAD
问题:不在任何分支上,无法 push
解决:
# 切换回主分支 git checkout main # 或创建新分支保存当前修改 git checkout -b new-branch
坑 7:GitHub 访问慢 / 连不上
解决:
# 使用 GitHub 镜像加速(临时) git config --global url."https://ghproxy.com/https://github.com/".insteadOf "https://github.com/" # 或修改 hosts 文件绑定 IP # Gitee 一般无需加速
四、推荐工作流
# 1. 克隆远程仓库 git clone git@github.com:用户名/仓库名.git # 2. 创建功能分支 git checkout -b feature/my-new-feature # 3. 开发并提交 git add . git commit -m "feat: 添加新功能描述" # 4. 推送分支到远程 git push -u origin feature/my-new-feature # 5. 在 GitHub/Gitee 上创建 Pull Request / Merge Request
五、Git 提交规范(推荐)
feat: 新功能 fix: 修复 bug docs: 文档更新 style: 代码格式(不影响逻辑) refactor: 重构 test: 测试相关 chore: 构建/工具变动
示例:
git commit -m "feat: 添加用户登录功能" git commit -m "fix: 修复首页加载超时问题"
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。


最新评论