Frequently Used Git Commands
Apr 5, 2021 11:06 AM
Updated At
Apr 30, 2021 03:21 PM
There are some questions I find myself repeatedly searching for the answer for in Git. Below I'll capture those repeated questions and their answer! It will certainly help me, and I hope it will help you.

Rename a branch

# The -m is the important part here!
# I read the below as "git branch move to newname"
git branch -m newname

Clean up a branch before committing

# <base-branch> could be master, main, trunk, dev, feature/three/times/removed
git rebase -i <base-branch>
Once your configured editor opens, you can change pick to squash to combine the commits. You could even reword the pick commit to provide a nicer name before you open your PR.

Move commits from master/main to new branch

git branch newbranch
# Go back 3 commits. This could be any number. You *will* lose uncommitted work.
# You can also specify a commit ref
git reset --hard HEAD~3
git checkout newbranch

Finding uncommitted changes from a git clean

Maybe. I highly recommend reading this SO post, and also this one. Here are the take-away commands:
git fsck --cache --no-reflogs --lost-found --dangling HEAD
# Then show the file
git cat-file blob <SHA> > filename.txt
# Get list of unreachable files that git knows a file name for
git fsck --unreachable --no-reflogs --no-cache HEAD | fgrep " tree " | cut -d " " -f3 | xargs -r -n1 git ls-tree | fgrep " blob " | cut -d " " -f 3- | sort -k2 -u