Here is the list of top five git commands which are most useful in my opinion.
1) Do you want to undo the last commit without losing changes?
git reset --soft HEAD~1
"~1" is for how many commits you want to undo. let's say we want to undo last 2 commits then we can use
git reset --soft HEAD~2
which will return us the files changed in the last two commits
how this can be used with other commands let check that out.
let's say we want to remove the last commit from git history.
then we can simply
git reset --soft HEAD~1 git push -f
Note: use -f carefully
2) Imagine you are working on some tasks and suddenly the manager came to you and asked you to fix some bug.
this command will help you in saving your changes somewhere safe and you can get back this whenever you wanted.
git stash will temporarily save your changes we can get these changes back by using
git stash apply
3) A case where we don't want to merge conflicts. And we don't want to do any merge using git merge then.
let's say we are in branch XYZ and we made one commit and when we raise PR we are getting merge conflicts.
git reset --soft HEAD~1 ->get's the change of the last commit git stash ->stores them temporally git reset --hard origin/develop ->reset the branch with the develop ->not current branch files are replaced by develop files git stash apply ->will get the changes back from the last commit git commit -m "message" git push -f
- The same thing can be achieved by using the merge and rebase but I feel it is more comfortable using this.
- Commit message will be removed in this process so we have to add commit message again
- The same above commands can be used when we want to have a single commit for one task replacement for amend as well.
4) Have you ever came across the situation where you need to add the few more files to the same commit without changing the commit message? Then this command is for you.
git commit --amend --no-edit
git commit will commit the files and --amend will add the additional files to the commit and --no-edit will make sure that we use the same commit message.
note: if we use --amend without --no-edit terminal will prompt an option to edit the commit message
5) Have you wonder how to reset particular file content with the contents of another branch
let's say we are in branch XYZ and we need to update one file contents with develop branch.
git checkout develop <fileName>
This website, DEV, is a social media platform designed specifically for developers.