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


当前回答

注意!如果您只想从上一次提交中删除一个文件,并将其保存在磁盘上,请阅读上面juzzlin的回答。

如果这是您最后一次提交,并且您希望从本地和远程存储库中完全删除该文件,您可以:

删除文件git-rm<file>带有修正标志的commit:gitcommit--修正

修正标志告诉git再次提交,但“合并”(不是合并两个分支的意思)这次提交与最后一次提交。

如注释中所述,在这里使用gitrm就像使用rm命令本身一样!

其他回答

执行以下命令序列:

//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~1

并创建新的提交。

然而,有一个很棒的软件“gitkraken”。这使得使用git很容易。

我将用例子向你解释。设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 reset --hard @{u}

然后把东西复制回去。提交,推。