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!

Rollback commit

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 log

Rollback stage

If you stage your changes in some files that you want to unstage-

git restore --staged <file_name>

Rollback changes

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>

Rollback working tree

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 -n

It 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 -f

Split commit

Sometimes we want to split the commit into two or more, just like we do the opposite, merge.

Split most recent commit

git reset HEAD~

Then stage you changes as the way you want and commit them.

Change branch

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 world

The format can be viewed as-

git rebase --onto <new_parent> <old_parent> <child_branch>
⚠️ **GitHub.com Fallback** ⚠️