Common mistakes and recovery - Anjum219/Git-basics GitHub Wiki
Mistakes gonna happen when we start using git. We don't know clearly what a command does, but still we use it. Sometimes we get unexpected results and then understand, oh this is how the command is supposed to work. But in the meantime, we did some terrible mistakes. If you face this, you are lucky. Because, you are going to learn how to recover the mistakes and it will go a long way!
Let's start by rollbacking commits. You may have a typo in your commit. To change the last commit message-
git commit --amend -m "new message"Or you may not be ready to commit yet. But you want to keep the changes. So do this-
git reset --soft HEAD~<number_of_commits>You may accidentally merge some commits in your branch. Now you just want to forget it. To undo the changes-
git reset --hard HEAD~<number_of_commits>You can check commit history by-
git logIf you stage your changes in some files that you want to unstage-
git restore --staged <file_name>You may want to discard some changes that is not staged yet. Removing the --staged flag will be enough in that case.
git restore <file_name>You may have some untracked files, not yet added to the working tree. Suppose, you don't need these modifications. These changes are not staged or committed, so how can we discard them? By using git clean
git clean -d -nIt shows the modified files. If you want to keep any of these, you can use- git add <file_name>. Then write the following to discard rest of the modifications-
git clean -d -fSometimes we want to split the commit into two or more, just like we do the opposite, merge.
git reset HEAD~Then stage you changes as the way you want and commit them.
I got into a situation when I needed to change the parent of a branch. Suppose, you have a master branch and a branch named hello. Inside hello branch, you created another branch named world. You realise that world's commit should be over the top of master's commits i.e., the parent branch should be master. You have nothing to worry. Just do the following-
git rebase --onto master hello worldThe format can be viewed as-
git rebase --onto <new_parent> <old_parent> <child_branch>