Skip to content

Instantly share code, notes, and snippets.

@imonroe
Last active Jul 28, 2018
Embed
What would you like to do?
Handy Git tricks
## discard modifications in a directory
git checkout -- Gemfile # reset specified path
git checkout -- lib bin # also works with multiple arguments
## Undo local commits
git reset HEAD~2 # undo last two commits, keep changes
git reset --hard HEAD~2 # undo last two commits, discard changes
## Remove a file from the repo, but keep it in the filesystem
git reset filename # or git remove --cached filename
echo filename >> .gitingore # add it to .gitignore to avoid re-adding it
## Edit a commit message
git commit --amend # start $EDITOR to edit the message
git commit --amend -m "New message" # set the new message directly
## Add a forgotten file to the last commit
git add forgotten_file
git commit --amend
## Clean up local commits before pushing
## Good for squashing
git rebase --interactive
# if you didn't specify any tracking information for this branch
# you will have to add upstream and remote branch information:
git rebase --interactive origin branch
## Revert pushed commits
git revert c761f5c # reverts the commit with the specified id
git revert HEAD^ # reverts the second to last commit
git revert develop~4..develop~2 # reverts a whole range of commits
# undo the last commit, but don't create a revert commit
git revert -n HEAD
## Completely remove a sensitive file (secrets.txt) from a public repo
## CAUTION: this re-writes the history all branches and tags, and can be disruptive.
git filter-branch --force --index-filter \
'git rm --cached --ignore-unmatch secrets.txt' \
--prune-empty --tag-name-filter cat -- --all
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment