## push之前未pull 报错信息: ```bash D:\code\test\test1>git push origin master To http://192.168.1.189:8443/r/test.git ! [rejected] master -> master (fetch first) error: failed to push some refs to 'http://192.168.1.189:8443/r/test.git' hint: Updates were rejected because the remote contains work that you do not hint: have locally. This is usually caused by another repository pushing to hint: the same ref. If you want to integrate the remote changes, use hint: 'git pull' before pushing again. hint: See the 'Note about fast-forwards' in 'git push --help' for details. ``` 解决方法: ```bash # 先拉取 git pull # 后推送 git push origin master ``` **注意:** 不要强推,可能覆盖他人修改,一般用不到。 ```bash git push -f origin master ``` ## 合并冲突(修改同一文件) 当 A 和 B 同时修改了同一文件的时候,本地文件和远程文件发生了冲突。Git 无法自动合并,需要你手动解决冲突。 例如: ```bash CONFLICT (content): Merge conflict in a.txt Automatic merge failed; fix conflicts and then commit the result. ``` 意思是: - Git 在合并文件 `a.txt` 时,发现本地和远程对同一部分代码进行了修改; - 无法判断以哪一方为准,自动合并失败; - 需要你手动处理这个冲突。 解决方案: 1. 打开冲突的 `a.txt` 文件,查看里面的内容: ``` <<<<<<< HEAD 12 # 这里是 A 修改的 ======= 1 # 这里是 B 修改的 2 >>>>>>> 6fe1e2d97eae79e0c5080ddea4bdef658841486d ``` 2. 手动修改内容,保留需要的部分。例如: ``` 12 ``` 3. 添加修改后的文件: ```bash git add a.txt git commit -m "解决 a.txt 冲突" git push origin master ``` ## 修改文件但 git status 显示未修改 可能的原因: - 你改的是换行符(LF/CRLF)但内容没变; - 编辑器保存规则设置导致未检测到真实修改; - 文件编码问题或隐藏字符。 解决方法: - 用 `git diff` 检查是否真的修改了; - 也可以尝试先改点内容,再恢复,重新保存。 ## 误删文件 ### 文件误删并已 add 误删了一个文件(比如 `b.txt`),然后执行了: ```bash git add a.txt ``` - 这时候 Git **把删除操作加入暂存区**,等待 commit。 - 文件还没有被 commit,但已经从工作区和暂存区记录为“删除”。 **查看哪些文件被误删** ```bash git status ``` 示例输出 ```bash Changes to be committed: (use "git restore --staged ..." to unstage) new file: a.txt Changes not staged for commit: (use "git add/rm ..." to update what will be committed) (use "git restore ..." to discard changes in working directory) deleted: a.txt ``` **恢复文件** 这会把文件从暂存区移除,但 **不会恢复工作区文件**。 ```bash git restore --staged a.txt ``` 这会把文件从最后一次 commit 的版本恢复到工作区。 ```bash git restore a.txt ``` 或者可以循环恢复多个误删文件: ``` git restore --staged . git restore . ``` > `git restore .` 会把所有误删且未 commit 的文件恢复。 ### 文件已 commit,误删未 add 场景说明 - 文件 **已经被 Git commit**(也就是之前已经被保存到版本历史中) - 你在工作区 **误删了该文件** - **还没有执行 `git add`** > 这时候 Git 知道文件原本存在,但工作区已经缺失。 **查看被误删的文件** ```bash git status ``` 示例输出: ```bash Changes not staged for commit: (use "git add/rm ..." to update what will be committed) deleted: a.txt ``` > 🔹 `deleted: a.txt` 就是被误删的文件。 **恢复误删文件(未 add)** ```bash git restore a.txt ``` > 这会从 **最近一次 commit** 恢复文件到工作区。 **检查文件是否恢复成功** ``` git status ``` - 文件会出现在工作区 - `git status` 不再显示 `deleted`