Git Snippets
warning
Some of the snippets changes commit history. Use with caution.
Stage case-sensitive file changes
git mv --force old_name NEW_NAME
Remove commits after a certain commit
git rebase --committer-date-is-author-date -i <commit-hash>^
Reset author
- Configure the author name and email. (Add
--globalto set the author globally.)
git config user.name "New Author Name"
git config user.email "<email@address.example>"
- Rewrite the commit history.
git rebase -r '<since-commit-hash>' --exec 'git commit --amend --no-edit --reset-author'
or from the top
git rebase -r --root --exec 'git commit --amend --no-edit --reset-author'
Remove ignored files from local file system
This resets the local file system to a clean state. e.g. Remove installed node_modules or built files.
git clean -fdX
Remove checked-in ignored files
- Update
.gitignoreto exclude the files. - Remove the files from the repository.
git rm --cached `git ls-files -i -c --exclude-from=.gitignore`
- Commit the changes.
Undo a commit
git reset --soft HEAD~1
To discard the changes:
git reset --hard HEAD~1
Commited to the wrong branch
warning
You'll need to force push the changes if the commit is already pushed.
- Create a new branch from the commit.
git branch new-branch
- Update the current branch to the previous commit.
git reset HEAD~ --hard
- Switch to the new branch.
git checkout new-branch
Update author and committer of the latest commit
git commit --amend --no-edit --reset-author --date="$(git show -s --format=%ci HEAD)"
Note: This will update commit timestamp, in most case, you should.
Wipe files from the history
There's a git command called filter-branch, but newren/git-filter-repo (0) is a faster, safer modern alternative.
- Filter the branch to remove the file from the entire history.
git filter-repo --path-glob '*.png' --invert-paths
- Re-add your origin back if it is removed by
git-filter-repo - Push the changes to the remote repository.
git push --force-with-lease
References
- Oh Shit, Git!?!: Some useful snippets