如何优雅的使用Git
  • 2022-06-19 14:14:30 添加 git 放弃文件修改,git 暂存文件修改部分

git初始化本地仓库

1
git init

此操作会生成一个.git文件,默认情况下是隐藏的。

git仓库clone到本地

1
git clone HTTPS/SSH

git本地项目提交到云端

以下操作默认远程仓库分支为master。

1
2
3
git add .     (git add隔空格.)
git commit -m "提交信息" (注:“提交信息”里面换成你需要,如“first commit”)
git push -u origin master (注:此操作目的是把本地仓库push到github上面,此步骤需要你输入帐号和密码)

如果push失败,可能的原因:

(1)本地库与远程库内容不一致,此时需要执行命令:

1
git pull origin master

(2)远程和本地仓库分支不一致,git更改仓库分支,把本地的 master 仓库名称修改为远端的 main

1
git branch -m oldBranchName newBranchName

(3)本地的origin和remote origin/master 没有建立关联,此时重新建立本地和远端的连接

1
2
3
git remote remove origin
git remote add origin git@github.com:XXX/XXX.github.io.git
git push origin master

(4)本地文件与github上的文件有冲突/本地需要提交的文件中存在空文件

1
2
3
4
touch README
git add README
git commit -m "change"
git push origin master

git 撤销本地修改

(1)未使用 git add 缓存代码

1
2
git checkout .                      // 放弃所有文件修改
git checkout -- filepathname // 放弃filepathname文件修改

(2)已使用 git add 缓存代码

1
2
git reset HEAD .                  // 放弃所有缓存
git reset HEAD filepathname // 放弃指定文件的缓存

此命令用来放弃 git 对已修改文件的缓存,相当于撤销 git add 所作的工作。

执行此命令之后文件状态回到(1)步状态,如果需要彻底放弃文件修改,可以使用(1)的命令。

(3)已使用 git commit 提交代码

1
2
git reset --hard HEAD^              // 回退到上一次的commit状态
git reset --hard commitid // 回退到指定的commitid版本

git 暂存文件修改

1
2
3
git stash         // 将修改的代码先暂存起来,将本地仓库恢复到最后一次提交的状态
git stash pop // 恢复之前暂存的文件修改,默认恢复最后一次的stash结果
git stash list // 查看暂存的stash列表

参考文章:https://www.cnblogs.com/tugenhua0707/p/4050072.html

Author: wnxy
Link: https://wnxy.xyz/2021/04/27/Git-usage/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.