如何从最新提交中删除文件?


当前回答

我将用例子向你解释。设A、B、C为3次连续提交。提交B包含一个不应提交的文件。

git log  # take A commit_id
git rebase -i "A_commit_ID" # do an interactive rebase
change commit to 'e' in rebase vim # means commit will be edited
git rm unwanted_file
git rebase --continue
git push --force-with-lease <branchName>    

其他回答

如果你还没有将你的更改推送到git

git reset --soft HEAD~1

它将重置所有更改并恢复为一次提交

如果这是您最后一次提交,并且您希望从本地和远程存储库中删除文件,请尝试以下操作:

git rm <file>
 git commit --amend

甚至更好:

先重置

git reset --soft HEAD~1

重置不需要的文件

git reset HEAD path/to/unwanted_file

再次提交

git commit -c ORIG_HEAD  

这是我从比特桶回购中删除文件的工作,我最初将文件推送到分支。

git checkout origin/develop <path-to-file>
git add <path-to-file>
git commit -m "Message"
git push

执行以下命令序列:

//to remove the last commit, but preserve changes  
git reset --soft HEAD~1

//to remove unneded file from the staging area  
git reset HEAD `<your file>` 

//finally make a new commit  
git commit -m 'Your message'

同样的问题是,我在本地分支中进行了更改,我只想恢复一个文件。对我有用的是-

(下面的feature/target_branch是我所有更改的地方,包括我想撤消的特定文件的更改)

(origin/feature/target_branch是我要将更改推送到的远程分支)

(feature/stating是我的临时暂存分支,我将从所有需要的更改中推送,不包括对该文件的更改)

从我的原点/feature/target_branch创建本地分支-称为feature/stating将我的工作本地分支feature/target_branch合并到feature/stating分支签出功能/暂存,然后git reset--soft ORIG_HEAD(现在将暂存功能/暂存的所有更改,但未提交。)取消对我以前签入的文件进行不必要的更改将feature/stating的上游分支更改为origin/feature/target_branch提交其余的阶段性更改,并向上游推送到我的远程原点/feature/target_branch

如果出于任何原因(就像我的情况一样),您在重新设置上次提交的所有文件时遇到困难,如git reset--soft HEAD^,并且您的情况满足以下条件,您可以按照我下面的解释进行操作。

您试图删除的文件在上次提交之前已存在于存储库中您可以撤消自上次提交以来文件中的所有更改(HEAD~2-上次提交之前的提交)

然后,您可以撤消自上一次提交(HEAD~2)以来的所有更改,保存文件,将其暂存(git-add文件名),然后运行gitcommit--modify--no edit。这将提交“新的更改”,这实际上是将文件重新提交到上次提交之前的最后一次提交。