git,

Git: tips and tricks

Nov 06, 2022 · 2 mins read · Post a comment

You can’t really much think of any projects that’s being developed today without Git. Git is one of the fundamental core tools when writing software in a team or even by yourself. Although from my personal experience I haven’t used more than 5 Git commands on a daily basis, here’s some neat tips and tricks that could ease your day-to-day development.

Prerequisites

  • Git

Solution

empty commits

When dealing with CI/CD pipelines whatever it was developing, testing or debugging you might want to test things out using blank commits. This is done by running:

git commit --allow-empty -m "Trigger deployment"

Related: How to create and push empty Git commits.

cleaning up your repo

Being a Git repo janitor is sometimes a must especially if dealing with loose objects. The holy command that could help you remove any unreachable, dangling or orphaned Git commits is the following one:

git gc --aggresive --prune=now

Related: Git gc.

remove any local stale branch

Regarding stale, old branches that have already being merged into the main branch and no longer exists in remote, you can do the following:

  1. Open your ~/.gitconfig file and add the prune option.
    [fetch]
      prune = true
    
  2. Save.

You can also do the same with: git config --global fetch.prune true.

Alternately, if you want to get rid of every local branch except main and maybe develop, execute the following command:

git branch | grep -v "main\|develop" |  xargs git branch -D

Related posts:

saving uncommitted work

Switching between multiple branches is not a rare thing to do, often linked to fixing bugs. Now, if you need to save your uncommitted changes before jumping to another branch, stash your changes first:

git stash

The moment you want to continue with your work, checkout the branch and apply the saved changes:

git pop

If you just want to remove the changes and start over, run: git stash drop. Also, keep in mind that you might get into a Git conflict situation if some of stashed files are already being updated.

Related: Git 101: git stash.

resetting your work

Undoing all your work is not something you want to happen often, but sometimes it does regardless if there was a shift of priorities or whatever else right. To undo all your current work including local commits, run:

git reset --haed HEAD

Conclusion

To find more neat Git commands and hacks, simply browse the Git category. Feel free to leave a comment below and if you find this tutorial useful, follow our official channel on Telegram.

git