Today, I will share some common mistakes we face while using git and how to tackle them with ease. So let's get started.
Q. Revert changes that are not staged yet.
- you can simply use
git checkout
to revert these changes
Q. correct the commit message
- use
git commit --amend -m "new commit message"
Note: this will change the commit hash, as commit message is the part of hash. So only use this if you're working alone or your commits are not pulled by other devs
Q. forgot to add a file in your commit
- add the file to staging and run
git commit --amend
, save and exit the commit message file that opens after this command.
Now let's move to something more serious.
Q. If you made commit to master branch by mistake which were meant to be committed on a feature branch.
- To the rescue comes, "git cherry-pick"
steps:
1) Run git log
and copy the hash which you want to move in feature branch.
2) git checkout <branch-name>
3) git cherry-pick <hash>
4) git log
, you will see the new commit
Now to remove that commit from master, use git reset
Q. Now say you ran git reset --hard
and you realize... that code was precious to your heart. The life saver is git reflog
steps:
1) run git reflog
, it will show you the history of activities
2) copy a hash before reset was done
3) run git checkout <hash>
4) you will be in detached head state, now make a backup branch
5) git checkout master
, your master branch is safe, precious code is safe in backup branch :D
Final one,
Let's say, you're in a situation where you want to revert the changes but other devs already pulled you work.
For that you have, "git revert"
git revert <hash>
It does not change the commit history, but makes new commits to reverse the changes. You can check using git diff <previous commit hash> <new commit hash>
, it does the exact opposite in those commits to bring back the code in it's previous state. Then you can push these changes to remote.
I will be back with more. Till then adios!
- mechtech5
Top comments (0)