Awesome git commands to rescue yourself

Git is confusing and if you are not using with presence mind you could f–k things easily in your daily development 😱

I have this list which helped me to come over the bad situations in git. I am writing these to remember the commands which can help in daily development using git as all these can easily be missed and finding command in git docs (https://git-scm.com/docs) lead to craziness:).

Extra Note

Git has three main states that your files can reside in are:

  1. committed (data is safely stored in your local database)
  2. modified (you have changed the file but have not committed it to your local database yet)
  3. staged (you have marked a modified file in its current version to go into your next commit snapshot)

Based on stages the three main sections of a Git project are:

  1. git directory (Git stores the metadata and object database for your project)
  2. the working tree ( A single checkout of one version of the project)
  3. the staging area ( It stores information about what will go into your next commit )

More details here link: Git-Basics

End

Git commands list which can bring back the smile 😃

  1. I need to change the commit message typo which I have just committed ( run commit command with --amend switch)

git commit --amend

  1. I just committed code and now I need to make small changes
    steps: make changes to your files and add them again

git add /project/changed_files
git commit --amend

  1. Added files (git add ) before seeing the changes/diff

git diff --staged or git diff --cached

  1. I have committed to master which need to be in a new branch
    (create a new branch from the current head state of master and remove the commits from the master head)

git branch new_feature_branch_name
git reset HEAD~ --hard

# (can only be used after the immediate commit to master and if 
# you have done multiple commits then need to use different git command )

  1. Undo the commit I just made
    (when you remembered what you just committed is incomplete and you are in wrong branch or whatever you think to revert the current commit)
    this can be used different scenarios

# i) just to reset the committed files from staging

git reset --soft HEAD^

# ii) committed to the wrong branch

git reset --soft HEAD^
git stash
git checkout -b new_branch
git stash pop

  • HEAD^ and HEAD~ are aliased each other