外观
常见问题
约 847 字大约 3 分钟
2025-06-19
目录
误推临时分支到远程
不小心把本地临时分支 push 到了远程,想要删除。
使用 git branch -r -d 只能删除本地对远程分支的追踪引用,并不能真正删除远程分支。正确做法:
git push origin :branch-name冒号前面的空格不能少。原理是将一个空分支 push 到远程,相当于删除该分支。
Git 2.9+ 也可以使用:
git push origin --delete branch-name
Pull 冲突:本地有未提交的修改
执行 git pull 时出现以下错误:
error: Your local changes to the following files would be overwritten by merge.
Please commit your changes or stash them before you can merge.
Aborting方案一:保留本地修改
git stash # 暂存本地修改
git pull # 拉取远程代码
git stash pop # 恢复暂存的修改然后使用 git diff -w <file> 确认自动合并情况。
方案二:丢弃本地修改,直接使用远程代码
git reset --hard HEAD # 丢弃所有未提交的本地修改
git pull # 拉取远程代码Push 到非裸仓库被拒绝
Push 代码到远程仓库时提示:
[remote rejected] master -> master (branch is currently checked out)
remote: error: refusing to update checked out branch: refs/heads/master
...原因
远程仓库不是裸仓库(用 git init 而非 git init --bare 创建),且当前正位于被 push 的分支上。Git 默认拒绝向当前检出的分支推送,因为这会导致工作区和索引不一致。
解决方案
方案一:在远程仓库的 .git/config 中修改配置:
[receive]
denyCurrentBranch = ignore注意:上面修改的是远程仓库的 config,不是本地分支的 config。
方案二(推荐):初始化远程仓库时使用裸仓库:
git init --bare方案三:在远程仓库切换到其他分支后再 push。
CRLF 换行符警告
出现以下警告:
warning: in the working copy of 'file.php', CRLF will be replaced by LF the next time Git touches it换行符概念
| 系统 | 换行符 |
|---|---|
| Windows | CRLF (` |
| `) | |
| Linux / macOS | LF (` |
| `) |
配置 core.autocrlf
git config --global core.autocrlf true各状态含义
| 值 | 提交时 | 检出时 | 说明 |
|---|---|---|---|
true | 转为 LF | 转为 CRLF | Windows 推荐 |
input | 转为 LF | 不做转换 | Linux / macOS 推荐 |
false | 不做转换 | 不做转换 | 不推荐,可能导致跨平台问题 |
误删文件恢复
文件刚删除,尚未 commit
git checkout -- <file> # 恢复工作区文件
# 或 Git 2.23+
git restore <file>文件已在 commit 中被删除
git log -- <file> # 找到文件最后一次存在的提交
git checkout <commit-hash> -- <file> # 从指定提交恢复文件文件已被 reset 丢弃
git reflog # 查看所有操作记录
git reset --hard <commit-hash> # 恢复到操作前的状态本地分支与远程分支不同步
git fetch --all # 拉取所有远程更新
git fetch --prune # 拉取并删除本地已不存在的远程分支引用