Git is amazing, I love it. Sometimes though I forget the various commands to do things. Come on admit it... you do too :) Anyway here's my list of useful git commands. Enjoy!

Reset local branch to origin branch

git fetch origin
git reset --hard origin/[branch]

Amend last committed message

git commit --amend -m "New commit message"

Amend specific commit

git rebase [commit_hash] --interactive

Amend multiple commits

git rebase -i HEAD~3
* ~3 means 3 commits

Delete local and remote branch

git branch -d [branch]
git push origin :[branch]

Abort pull

git reset --hard ORIG_HEAD

Abort merge

git merge --abort

Undo last commit but leave files staged

git reset --soft HEAD^

Undo last commit and also unstage files

git reset HEAD~1

Completely remove file from git history

git filter-branch --force --index-filter \ 
'git rm --cached --ignore-unmatch [file_name] l' \ 
--prune-empty --tag-name-filter cat -- --all

git push origin master --force

Rename author in git history

Place the following in a shell script. Make sure to provide the correct email addresses for both wrong@emailaddress.com and correct@emailaddress.com.

#!/bin/sh

git filter-branch -f --env-filter '

an="$GIT_AUTHOR_NAME"
am="$GIT_AUTHOR_EMAIL"
cn="$GIT_COMMITTER_NAME"
cm="$GIT_COMMITTER_EMAIL"

if [ "$GIT_COMMITTER_EMAIL" = "wrong@emailaddress.com" ]
then
    cm="correct@emailaddress.com"
fi
if [ "$GIT_AUTHOR_EMAIL" = "wrong@emailaddress.com" ]
then
    am="correct@emailaddress.com"
fi

export GIT_AUTHOR_NAME="$an"
export GIT_AUTHOR_EMAIL="$am"
export GIT_COMMITTER_NAME="$cn"
export GIT_COMMITTER_EMAIL="$cm"
'

Then run:

git push -f

Undo last pull

git reset HEAD@{1}


comments powered by Disqus