Squash several Git commits into a single commit

When we are working in any project in git, over a period of time there are a large number of commits are added in git. The best course of action is to always work in a branch and the keep working with you pace and adding commit. When you reach a point where you want to merge changed to master branch and wants to squash multiple commit into single with detailed description.

The easiest way to turn multiple commits in a feature branch into a single commit is to reset the feature branch changes in the master and commit everything again.

# Switch to the master branch and make sure you are up to date. 
git checkout master 
git fetch # this may be necessary (depending on your git config) to receive updates on origin/master 
git pull # Merge the feature branch into the master branch. 
git merge feature_branch # Reset the master branch to origin's state.
# This is important, here after merge you are resetting the master branch head
git reset origin/master # Git now considers all changes as unstaged changes. 
# We can add these changes as one commit. 
# Adding . will also add untracked files. 
git add --all 
git commit

Note that this is not touching the feature branch at all. If you would merge the feature branch into the master again at a later stage all of its commits would reappear in the log.

You may also do it the other way round (merging master into the branch and resetting to the master state) but this will destroy your commits in the feature branch, meaning you can not push it to origin.