Git most common mistakes and how to fix them

In this article, I will discuss common mistakes programmers made while using Git and how to solve them. 

1. Spelled last commit message wrong
Spelling mistakes are very common in most of the developers. Luckily, there’s a simple fix.

This will open up your editor and allow you to make a change to that last commit message.

2. Spelling mistake on the branch name
There’s a solution for this too. We rename this branch in a similar way to how we rename a file with the mv command: by moving it to a new location with the correct name.

If you have already pushed this branch, there are a couple of extra steps required. We need to delete the old branch from the remote and push up the new one:

3. Accidentally committed all changes to the master branch
So you are working on a new feature and in your hurry, you didn’t remember to start up a new branch for it. You have already committed a lot of files and now those commits are on the master branch.

So we can move all those changes to a new branch with the following three commands:

Note: Make sure you commit or stash your changes first, or all will be lost!

This makes a new branch, then rolls back the master branch to where it was before you made changes, before finally checking out your new branch with all your previous changes intact.

4. Forgot to add a file to that last commit
Another common Git mistake is committing too early. You skipped a file, forgot to save it, or need to make a small change for the last commit. --amend is your friend once again.

5. Added a wrong file in the repo
What if you added a file that you didn’t want to commit? A rogue ENV file, a build directory, a picture of your dog that you accidentally saved to the wrong folder?

If all you did was stage the file and you haven’t committed it yet, it’s as simple as resetting that staged file:

If you have already committed that change, no need to worry. You just need to run an extra step before:

6. Too many mistakes and your repo is in a worse state
Suppose you have made a mistake in your repo and to solve this you have copy-pasted one too many solutions from Stack Overflow. Now your repo is in a worse state than it was when you started. We have all been there.

git reflog shows you a list of all the things you’ve done. It then allows you to use Git’s magical time-traveling skills to go back to any point in the past.

If you want to go back to any point in the history, run the below command, replacing {index} with that reference, e.g. dfa27a2.

Have some Git tips of your own? Let us know in the comments below, I’d love to hear them.

Leave a Reply

Your email address will not be published. Required fields are marked *