Skip to content

Instantly share code, notes, and snippets.

@markuszeller
Last active March 23, 2020 11:08
Show Gist options
  • Save markuszeller/f3d2a5ab33cd7bd0da9f3bedc413fb51 to your computer and use it in GitHub Desktop.
Save markuszeller/f3d2a5ab33cd7bd0da9f3bedc413fb51 to your computer and use it in GitHub Desktop.
Remove a file from git repository

Remove a file from git repository

This will rewrite the complete history and remove a file from history. This is useful if you have a repository and added files you want to remove for reasons like accidential credentials or too large files (github now supports up to 100MB).

Use following command in your bash

git filter-branch -f --index-filter 'git rm --cached --ignore-unmatch FILENAME' HEAD
git gc --aggresive
git push

There is a nice java tool recommended by git called bfg repo cleaner which is capable of deleting large blobs.

Find a file manually

When you search the commit where a file was added or removed you can use git log to search the history.

git log --full-history --summary -- path/file

Allow only specific file patterns

For some repositories it makes sense to include only a certain file type. Here is an example to only keep xml files inside the /jobs directory or Markdown files in the root.

/*
!/jobs/*.xml
!/*.md

The exclamation mark does the inverse of exclude, so it forced to include.

  • Ignore all files
  • Do not ignore xml files in the jobs directory.
  • Do not ignore md files

Ignore files (globally)

To prevent files being pushed into the (public) repository, create a .gitignore file at the project root. List all files or directories as a pattern.

Ignore files (locally)

Sometimes files like configurations are needed locally and globally. Once pushed to the repository, you want to change it locally, but not push the changes.

Add those files to .git/info/exclude. If it was changes before and git status gives you a change, unstage it with

git update-index --skip-worktree filename

Get back to last commit

Reset all changed files back to the last committed version.

git reset --hard

When automerging fails, add the latest commit hash after --hard

If there are changes left, because files or directories are new, you can delete them by doing following, command where -d is for dirs and -f for files.

git clean -fd
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment