How to Move Git Branch Pointer to Different Commit

  1. Moving a branch pointer to another commit
  2. The git branch Command

Moving the branch pointer of a checked-out branch can be done with the git reset command followed by the --hard option. But the given command cannot handle the situation like moving the branch pointer of a non-checked out branch to point at different git commit.

Moving a branch pointer to another commit

If you want to move a non-checked out branch to another commit, the easiest way is running the git branch command with -f option, which determines where the branch HEAD should be pointing to:

git branch -f <branch-name> <sha1-commit-hash>
Be careful as this won't work if the branch you are trying to move is your current branch.

To move a branch pointer, run the following command:

git update-ref -m "reset: Reset <branch-name> to <sha1-commit-hash>" refs/heads/<branch-name> <sha1-commit-hash>

The git update-ref command updates the object name stored in a ref safely.

The git branch Command

Branches are an essential part of an everyday Git workflow. The git branch command is designed to create, list and delete branches but doesn’t allow switching between branches. The command is integrated with the git checkout and git merge commands. Generally, Git branches are a pointer to a snapshot of the changes. A newly created branch encapsulates the changes when you want to fix bugs or add features. This helps clean up the future's history before merging it.


Do you find this helpful?

Related articles