Skip to content

Git Remove

Kenneth Kasajian edited this page Aug 16, 2019 · 17 revisions

Removing stuff

git rm <files>
commit

If the file was modified, use -f to force removal.

If you accidentally added a file to git and wish to remove it only from git, but not the disk, use:

git rm --cached (filename)

Using wild-cards with rm requires backslash. eg.:

git rm log/\*.log
git rm \*~

Reset and sync local repository with remote branch

git fetch origin
git reset --hard origin/master
git clean -f -d

Undo

After doing an add (but not commit), if you change your mind, you can issue:
git reset HEAD <file>

to undo the add.

To undo changes to a checked out file, prior to commit:
git reset --hard

Or one file at a time:

git checkout myfile.txt
To fix the last commit message:
git commit
git add forgotten_file
git commit --amend

Another way - forgot something in the last commit:

git reset --soft HEAD^
git add forgot.txt these.txt files.txt
git commit
To undo a commit:
  git reset HEAD^

or to fix the last commit message:

Reversing stuff

Moving current local branch back one commit

git reset HEAD~

git reset will move HEAD and the current branch back to wherever you specify, abandoning any commits that may be left behind. This is useful to undo a commit that you no longer need. This command is normally used with one of three flags: "--soft", "--mixed", and "--hard". The soft and mixed flags deal with what to do with the work that was inside the commit after you reset, and you can read about it here

Never use git reset to abandon commits that have already been pushed and merged into the origin

The destination may be a relative reference, a commit Id, a tag or a branch name. Unlike 'checkout', 'reset' will move both HEAD and the current branch to the destination

Reverting stuff

Moving remote branch back one commit

git revert <commit-id>

To undo commits that have already been pushed and shared with the team, we cannot use the git reset command. Instead, we have to use git revert. git revert will create a new commit that will undo all of the work that was done in the commit you want to revert.

Refreshing a repository after changing line endings

git add . -u
git commit -m "Saving files before refreshing line endings"

git rm --cached -r .

git reset --hard

git add .
git commit -m "Normalize all the line endings"

References