How many times I’ve started an operation in Git and wanted to erase all to start again? Too many.
I’ve started a merge, but figured out that I was in the wrong branch.
I’ve started a rebase, but forgot to pull the target branch.
Here are 5 commands I use to never get lost with Git.
Fetch
Seems pretty obvious, but always start an operation with a git fetch.
This will update all the references in Git. Only the remote references, but that’s the point number two.
Use Origin Branches
Instead of switching to a branch, and then pulling it, I always use the remote branches.
I will never push on the main or release branch. Those are protected branches, so why try to maintain the local copy of the main and release branches up to date?
When creating a new branch:
git switch -c my-new-branch origin/main
When rebasing:
git rebase origin/release
As I’ve already fetched the remote references, I’m sure the origin is up to date.
Reflog
I’ve done a commit amend, or a rebase interactive and lost my previous reference.
How to go back? Those commands override the history. There is no simple way to go back.
Still, I can print the history of my positions with:
git reflog
This will print the commit’s hash of each of my previous positions. Then, I can simply go with:
git switch --detach <hash>
From there, I can see the commit or put the old branch back. How? Keep reading.
Abort
I’ve started a merge, but figured out that I was in the wrong branch.
I’ve started a rebase, but forgot to pull the target branch.
Solving conflicts may be very confusing.
How do I stop all this? All those commands have the abort option to stop everything and come back to the initial state.
git merge --abort
git rebase --abort
git cherry-pick --abort
If I have any doubt about solving the conflicts, the best solution is to abort, take a ride, talk to someone and start again.
Reset a branch
After completing the merge, I see that the result isn’t the expected.
Or the cherry-pick misses some other commits.
How do revert all my work when it’s already in the Git history.
I first find the commit’s hash where I know everything was stable.
Then, take my branch and forces it to the stable commit.
git switch --detach <stable-hash>
git branch -f my-branch
git switch my-branch
This way, I can start again with my branch in a stable position.
Those are some tricks I teach to newcomers when they try some complicated manipulations without clearly knowing what they do.
When using Git, I must always know where I am and where I want to go.
If you want to learn more about good quality code, make sure to follow me on Youtube.



Leave a comment