Git commands that can save your life

All of us know that git is quite a useful tool. However the smallest of mistakes, can make something drastically go wrong, and we (atleast I) would be blaming git for something useless that I did. Here are a few commands that I found useful from quite a few links. Hope you find them useful too.

1. Suppose you push in a commit to master instead of your current branch, due to some mistake, this can get your master back to track.

git checkout master
git remote update  # updates your remote
git reset --hard upstream/master  # resets your master to upstream
git push origin +master  # assuming your origin is umm.. well origin

Now you can to your branch and do git push origin

2. Suppose you have wrote a completely wrong commit message, or you would want to add something to your commit, that you forgot to add, and you do not want to push in another commit, this would be useful.

# Make whatever changes you want to do
git commit -a --amend
# This opens an editor. Change the commit message if you want to do
git push -f origin branchname

3. Suppose you pushed in a commit which is terribly wrong, and you want to undo it, so that it returns to its previous state. Then do this

git rebase -i master
# This is an interactive rebase.
# In the text editor that opens, just remove the commit that you want to delete
git push -f origin branchname

4. The most useful IMHO that I discovered recently, is

git reflog
# This will give you a list of changes that you made to the given branch
git reset --hard HEAD@{n}  # The nth state where you want to go
# This remove alll changes from the nth commit to the present commit.
git push -f origin branchname

As I discover more and more of git, I shall update it here. Cheers.



    1. Thanks a lot 🙂

  1. In the 4th one, I generally prefer git reset –hard instead of using HEAD@{n}, makes it even more precise.
    Also, have a looking a cherry picking between branches though simple but are very very helpful sometimes. ^_^

    1. git reset –hard reverts it back to the state before any commits were made right? Could you give an example of how cherry pick actually works?

  2. Whoops, I meant git reset –hard ###hash so that it is more accurate.

    Cherrypicking works commit by by commit, you can take a particular commit from a branch and push to the other, (only that commit) via that. It’s usually used for backporting to the deployed branch.

    1. Great thanks 🙂

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: